score:0
Appended new state to the previous other than replace, code may be 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));
}
}
score:0
setState
works asyncrounsly and it's possible that the state is not updated when you call console.log
in then
. setState
actually accepts a callback as its second argument, in which you can check the updated state:
this.setState(() => {...}, () => { console.log(this.state.data) })
Btw, considering your new state doesn't rely on the previous state, you can just pass an object to setState
instead of a function:
this.setState(
{
data: res,
...
},
() => {
console.log(this.state.data)
}
)
score:0
Try the following...
Change your setState
to setState({...})
and
remember the loading
import React, { Component } from "react";
const arrayOne = [
{
id: 1,
nome: "Ruan"
},
{
id: 2,
nome: "Paul Symon"
},
{
id: 3,
nome: "Renan Lucas"
}
];
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>Carregando...</h1>
) : (
<div>
{this.state.data.map((i) => {
return <h1>{i.nome}</h1>;
})}
</div>
)}
</div>
);
}
}
Source: stackoverflow.com
Related Query
- Can't assign response data to the state data and the response is not empty in React
- I listen the data from socket.When I receive the data, I update the array like this .but state is not updated.Please help me and thanks in advance
- API data not being copied and stored into the state in react, how would I do this?
- I am trying to load data from redux store on click and updating the state, but the data from state is not getting updated on the click
- ReactJS set state does not assign array from Axios response data
- List not rendering even when the array is not empty and the state is not null
- Is it possible to push data into state first and then return it by the push method, not spread or concat?
- FormData: The data is not placed in the formData, and an empty object is printed
- Why formData does not take the data there is in the state and that has been refreshed, there is a delay character ? React
- How to create state and assign the rows of material-ui-table with static data
- How can mock the value of a state and data in my react test
- setTimeout() function is not detecting a state change and keeps executing the recursive function
- Is it a bad practice to use state in a React component if the data will not change? Should I use a property on the class instead?
- data is fetched but the state is not updated
- how to display and map the first id of an state or const data array objects?
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- What is the diferent about data that defined inside the state and outside state that create inside the constructor?
- I am trying to render the names on my screen using "Rick and Morty" REST API,but nothing literally renders and my state is not updating
- Sending state for an Axios POST and data not showing in req.body
- How do I autofill the other autocomplete values based on the selected data and also add the data if it does not exist yet?
- wrote a React code snippet to implement conditional rendering and am not able to update the state of {Left} and {Right}
- How get data from the state and edit the element in the form?
- React-Table getting data of a specific row and Set in to the state
- JSON is not handled properly in react and not saved in the state
- React - setting state with data does not work/ sets its to an empty array - why?
- Why is React state the init state and not the state I just set?
- Im trying to build a menu that has collapsible options, but the dom does not update even when state data updates
- I have a data inside the state in T and Z format and React input accepts in the HH:MM ss format so how to convert
- Data Response Not able to map in the react router
- React JS: previousState in setState is not keeping the data of the previous state after the state is updated
More Query from same tag
- Cannot read property 'emit' of undefined when trying to emit a document
- React Native - make image size not change when keyboard is open?
- React native, error adding a root view
- Why getDerivedStateFromProps is called after setState?
- How to update state array dynamically in React?
- Looping Audio with React.js
- Uncaught TypeError: _this3.chooseTopic is not a function ReactJS
- Test redux reducers with Immer
- Slice and Map an array in Javascript but not seeing sliced array appear
- How to find latest 10 dates element from JSON object in React
- React: sending FormData to the server returns {}
- ES2015: How can I simplify an if statement with assignment?
- How to pass a JSON data from React to Django using POST request?
- How to hide multiple fields in react-admin ShowView?
- Why not use cookies instead of Redux?
- Testing window with renderHooks
- Handle multiple input value change within an object
- How to set icons on the right side of an Appbar using material UI
- How expand typescript type?
- Why is mapbox rejecting my geojson as invalid.
- Login with Firebase/auth - firebase__WEBPACK_IMPORTED_MODULE_3 __
- How can I get an instance of the Cesium viewer from document?
- Material-UI center button text ignoring icons
- How to displays data from useEffect hook?
- Attempted import error: 'App' is not exported from './App'
- How to correctly Type a React Component that is a param of a Function?
- Why, with ReactJS, am I failing to make checkboxes that react to being clicked?
- React JS Get Sum of Numbers in Array
- Get browser console to show filename + line number in javascript file
- Reactjs : Passing array as prop to child function component. Modifying the array in child is causing state mutation exception