Struggling to update state data with response data in React, despite the response not being empty

I'm currently working on my first React API application and I am facing an issue where the state data appears to be empty even after assigning res.data, which is not empty. Additionally, I am struggling with rendering all of this content inside a div.

When I console.log res.data, here is what it returns:

(2) [{…}, {…}]
0: {user: {…}, available_amount: 4324324}
1: {user: {…}, available_amount: 43243243}
length: 2
__proto__: Array(0)

Below is a snippet of my code:

  class App extends Component{
        constructor(props) {
        super(props);
        let data;
        this.state = {
          data: [],
          loaded: false,
          placeholder: "Loading"
        };
      }
    

    async componentDidMount(){
        let data;
        axios
            .get('http://127.0.0.1:8000/api/',{
                headers:{
                'Authorization': 'Token 8651a2b6c28ecd5cd25c0e67dfd7f3642a3d0029'
                }
            })
            .then(res => {
                this.setState(() => {
                    return {
                    data: res,
                    loaded: true
                };
                });
            })
            .then(console.log(this.state.data))

    }

Answer №1

Added new state to the existing state instead of replacing it, the code could look something like this.

class App extends Component {
  constructor(props) {
    super(props);
    let data;
    this.state = {
      data: [],
      loaded: false,
      placeholder: "Loading",
    };
  }

  async componentDidMount() {
    let data;
    axios
      .get("http://127.0.0.1:8000/api/", {
        headers: {
          Authorization: "Token 8651a2b6c28ecd5cd25c0e67dfd7f3642a3d0029",
        },
      })
      .then((res) => {
-        this.setState(() => {
-          return {
-            data: res,
-            loaded: true,
-          };
-        });
+        this.setState((prev) => {
+          return {
+            data: prev.data.concat(res),
+            loaded: true,
+          };
+        });
      })
      .then(console.log(this.state.data));
  }
}

Answer №2

setState operates asynchronously, meaning that the state may not be updated by the time you check it with console.log inside the then callback. One way to handle this is to provide a second argument to setState, which is a callback function where you can access the updated state:

this.setState(() => {...}, () => { console.log(this.state.data) })

If your new state does not rely on the previous state, you can simply pass an object to setState instead of a function like so:

this.setState(
    {
        data: res,
        ...
    },
    () => {
        console.log(this.state.data)
    }
)

Answer №3

Here are some recommendations to improve your code: Update setState method with setState({...}) and make sure to include the loading property in your state

import React, { Component } from "react";

const arrayOne = [
  {
    id: 1,
    name: "John Doe"
  },
  {
    id: 2,
    name: "Jane Smith"
  },
  {
    id: 3,
    name: "Michael Brown"
  }
];

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: true
    };
  }

  async componentDidMount() {
    setTimeout(() => {
      this.setState({ data: arrayOne, loading: false });
    }, 1000)
  }

  render() {
    return (
      <div>
        {this.state.loading ? (
          <h1>Loading...</h1>
        ) : (
          <div>
            {this.state.data.map((item) => {
              return <h1>{item.name}</h1>;
            })}
          </div>
        )}
      </div>
    );
  }
}

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

Utilize rest parameters for destructuring操作

I am attempting to destructure a React context using rest parameters within a custom hook. Let's say I have an array of enums and I only want to return the ones passed into the hook. Here is my interface for the context type enum ConfigItem { Some ...

issue retrieving data from live website created with next.js

Hello, I've exhausted all possible avenues to identify the cause of the error occurring on my live website built with NEXTJS. I have observed that this error only occurs when I reload the website. It's worth noting that I can successfully login ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

How to organize a scalable business software using React?

Many of us are familiar with enterprise web applications that serve as the backbone for business data. These applications consist of multiple modules accessed through a single login authentication and role-based authorization system. Instead of users loggi ...

Repeated Values Issue in Material Ui List Function

Struggling to display only the newly added todo item in the list? Utilizing the material ui library for list creation, I have successfully displayed the new item. However, instead of showing just the specific value that was added, the entire array is being ...

Is there a way to display the button just once in a map function while still retaining access to the iteration value?

Utilizing formik within material-ui for a form has been quite productive. I've implemented a map function to print text fields and managed to display the Submit button only once by targeting the index. However, there's an issue when attempting to ...

When employing GraphQL Apollo refetch with React, the update will extend to various other components as well

My current setup involves using react along with Apollo. I have implemented refetch in the ProgressBar component, which updates every 3 seconds. Interestingly, another component named MemoBox also utilizes refetch to update the screen at the same int ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

What could be causing the missing key value pairs in my JSON parsing process?

I have set up a Rails backend to serve JSON data, such as the example below from 2.json: {"id":2,"name":"Magic","location":"Cyberjaya","surprise_type":"Great","instructions":"test","status":"awesome","pricing_level":3,"longitude":"2.90873","latitude":"101 ...

Detecting worldwide route adjustments in Nextjs 13

Is there a way to detect when my route changes in order to trigger a specific event? I want to be able to handle this change and take action accordingly. I am currently facing challenges with Nextjs 13 and its implementation of the app router. As per best ...

Redirecting in React with passed data

How can you navigate to a different Route in React by clicking on an element and sending some data to the new Route? onDaySelect = (e, day) => { this.setState({ selectedDay: day }, () => { console.log("SELECTED DAY: ", this.sta ...

There was a SyntaxError due to an unexpected token < appearing

I have been struggling for the past two weeks to find a solution to this issue, but without any success. I am using phpgrid from phpgrid.com, and I only encounter this error online when I upload it to the server. Each time I try to fill out a form with an ...

date selection event

Utilizing the DatePicker feature from Material UI v0, I have crafted a distinct component called DateField to showcase the DatePicker. Here is how it looks: render() { return ( <div> <DatePicker onChange={this.onChang ...

Steps to retrieve the JSON response using newman

After successfully testing the endpoint on Postman, I exported it as a collection and now running it using Newman on Jenkins CI. Command: newman run <POSTMAN_COLLECTION>.json -r json,cli The response.json file is generated in the current direct ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Signing up with DJ Rest Auth

One of the challenges I'm currently facing involves using dj-rest-auth, an authentication tool specifically designed for Django. Upon user registration, a verification email is automatically sent to confirm their email address. However, I am strugglin ...

Can someone clarify the actual version of webpack.js being used in my Ruby on Rails application with --webpacker=react configuration?

My tech stack includes Ruby 2.7.1, yarn 1.22.5, Rails 6.0.4.4, and node v16.13.1 I recently followed a tutorial on integrating React into my Rails project from this link The tutorial led me to install webpacker 4.3.0 automatically in my Gemfile.lock file ...

What are the reasons behind the min and max range method not providing accurate results?

I am in need of a method that can verify if a given value falls within the valid range of -064.000000 to -180.000000 and 142.000000 to 180.000000. The structure of my ranges object is as follows: "ranges": { "range1": { "min& ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...