Home > Enterprise >  state of list is not getting update
state of list is not getting update

Time:12-22

I am not able to figure out why state of list is not getting update. response.data is getting print in console.

function Products(){
           const [List ,setList] = useState([])
           useEffect(() => {
                      axios.get("http://localhost:8900/courses").then((response)=> {
                            setList((prevList) => [...prevList, response.data]};
                            console.log( response.data)
                            console.log( "list",List)
                            });
                      }, []);

i am expecting state of the list to be updated with the data

CodePudding user response:

i tried this demo and it's working perfectly. you need to be aware that setList is async as per this answer.

function apiCall() {
  return new Promise((resolve) => setTimeout(() => resolve(3), 5000));
}
export default function App() {
  const [List, setList] = React.useState([1, 2]);
  React.useEffect(() => {
    apiCall().then((response) => {
      setList((prevList) => [...prevList, response]);
    });
  }, []);
  return <div>{List.join(' ')}</div>;
}

CodePudding user response:

You have a typo error on your setList inside of Axios, you forgot to close the parenthesis and used a curly bracket instead.

setList((prevList) => [...prevList, response.data]}; // it should be ])

function Products() {
   const [List, setList] = React.useState([])
    React.useEffect(() => {
      axios.get("https://jsonplaceholder.typicode.com/users").then((response)=> {
          setList((prevList) => [...prevList, response.data]); // Error was here 
          console.log(response.data)
          console.log( "list",List)
      });
    }, []);
  return (
    <div>List: {JSON.stringify(List)}</div>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Products />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="root"></div>

CodePudding user response:

you may refresh the page. I hope it work!

  • Related