Error message: "The property does not exist on the type 'never' in the Axios response in Next.js."

I recently started working on a NextJs project and encountered a challenge with Axios. In my VS code editor, I tried to access (response.data.sliders) but received an error stating "Property 'sliders' does not exist on type 'never'.ts(2339)". Despite seeing the 'sliders' in console.log(response.data), the error persisted. Feeling frustrated, I almost posted a question here seeking help when suddenly the solution dawned on me! It worked like magic, so I decided to share both the problem and the solution for others facing a similar issue. To provide clarity, I will include a screenshot and a snippet of my project code. This is what console.log(response.data) displayed

Here is a snippet of my code:

import axios from "axios";
const IndexPage = (props) => {
  return (
    <main>
      <Section1 Section1Props={props.Section1Props} />
     
    </main>
  );
};


export async function getServerSideProps(context) {
  try {
    const response = await axios.get(urlGenerator("api/v1/frontend-configuration"));
    
    const data = await response.data;

    return {
      props: {
        Section1Props : data.sliders, // This is where the error occurred
      },
    }
    
  } catch (error) {
    console.log(error);
    
  }
  
}

export default IndexPage;

Answer №1

After some investigation, I finally pinpointed the issue to my axios import statement. The correct way to import axios is like this -

const { default: axios } = require('axios'); // or
const axios = require('axios').default;

Instead of doing it this way -

import axios from "axios";

Although I'm not entirely sure why this change fixed the problem, I'm relieved and hopeful that it may have resolved your issue as well. If you have any insights on why this adjustment worked, please share them here. Understanding the rationale behind it would greatly benefit my comprehension.

Answer №2

I was able to resolve my issue by defining the response variable like so

const responseData: AxiosResponse<any>  = await axios.get('https://api.github.com/users/maths032')
    
    
  alert(responseData.data.id)

and bringing in axios in this manner

import axios, { AxiosResponse } from "axios";

It may not be the most optimal solution, but it does the job for me.

Answer №3

According to information found in the axios documentation:

If you want to have TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with require(), you can follow this approach:

const axios = require('axios').default;

// autocomplete and parameter typings will now be available for axios.<method>

I required an ESM import, so here is how I accomplished it:

import axios, { AxiosResponse, AxiosError } from 'axios';
const Axios = axios.default;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jest test failing due to issues with a stateful React component containing an asynchronous function

I'm currently going through a Jest testing tutorial on Pluralsight that can be found here. Even though I have written the code exactly like the author, my test is not passing for some reason. Link to my Pull request on the author's repo: https:/ ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

Establishing the state in a separate React component

I've tried various solutions found in other posts, but I still can't seem to resolve this issue. My main goal is to update the state of one component from another component. Below is a simplified version of my code: function updateOtherState(n ...

Zip streaming is not functioning properly on the browser, although it is working fine on Postman

I have been working with a specific package to directly download a ZIP file in the browser. The frontend code I am using is as follows: await this.$axios .get( `/inspections/defects/download/${this.$route.params.uuid}`, { ...

What is the best way to open a shared session in nightwatch and either a new browser tab or window?

When I attempted to use .sendKeys('body', [client.keys.COMMAND+"t"]), NW successfully sent the keys but unfortunately a new tab did not open. ...

Submitting forms with Ajax without reloading the page can cause errors in Internet Explorer

Simply put: Upon clicking the login button in Firefox, Chrome, or Safari, the form is submitted correctly, running a validation via ajax and opening a new page. However, in Internet Explorer (version less than 9), the submission attempts to post to the c ...

PHP is unable to show items containing special characters such as double quotes and apostrophes

I am facing an issue with ordering food items. Names that do not contain apostrophes work fine, but those like Pasqua Nero D'Avola Sicilia are causing problems. I have tried replacing ' with \', but the issue persists. Here is the relev ...

The timestamp indicating when the local file was last modified, using JavaScript

My current JavaScript project involves reading XML files stored in the %appdata% directory using jQuery's $.ajax function. Because the file is located in %appdata%, my JavaScript code has the necessary permissions to read and write to the file. For e ...

What is the best way to stop an embedded mp4 video from playing when a dynamically generated button is clicked?

After making modifications to the QuickQuiz code found at https://github.com/UrbanInstitute/quick-quiz, I have replaced the img with an embedded mp4 video that loads from a JSON file. Additionally, I switched from using the original SweetAlert library to S ...

The current export script is experiencing difficulties when working with the next/image component

I am working on a project that I need to build and export, but I am facing an error during the process. Below is the build script found in my package.json file: "scripts": { "build": "next build && next export" } ...

Displaying information in form using ajax within the laravel framework

I am currently utilizing ajax to retrieve data from a database. While I am able to successfully retrieve the data on the backend, I am facing difficulties displaying it in the input field below. I have tried writing some code, but it seems that the JavaScr ...

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

Having trouble getting your jQuery/JavaScript function to detect the property "-webkit-clip-path"?

Exploring the clip-path feature of CSS has been a fun experiment for me. I have successfully implemented it in my project and am now trying to incorporate JavaScript to dynamically change the start/stop positions of the clip-path. Below is a snippet of my ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Ways to refresh the count of newly added div elements

Currently, I am working on a socket chat program that requires a badge to display the number of users in the chat room every time a new user joins. The code snippet provided below shows a function that adds the name of the new user to the list. The added n ...

Using function arguments as private variables in JavaScript allows for better encapsulation

Have you ever wondered if function arguments automatically become private variables within the function? I came across this interesting concept and decided to experiment: var node = function(nParent,nName,nContent){ this.init = function(){ ale ...

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...

What issue is present in this Node.js one-line conditional statement?

Check it out: ( result.username === user.username ) ? res.status( 500 ).json( "That username is already taken." ) : res.status( 500 ).json( "That email has already been used." ) Shouldn't this execute the first part, res.status( 500 ).json( "That us ...

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Using Ajax to set the file target dynamically

Let me start by saying that I prefer not to use JQuery for any suggestions. I'm not a fan of how JQuery has become the de facto standard within JavaScript. Now, onto my issue: I want to pass a variable to a function that will then use that variabl ...