2

App.js:

function App() {
  const [items, setItems] = useState([]);
  useEffect(() => {
    const searchDB = () => {
      fetch("http://127.0.0.1:8443/subColumns/5/?key=fc257229-8f91-4920-b71f-885403114b35", {
        mode: 'cors',
        credentials: 'include'
      })
        .then(res => res.json())
        .then((json) => {
          setItems(json);
        })
  console.log({items});
    }
    searchDB();
  }, [])

I need to keep the json response in a state varibale because in the future, the API request will nt be hard coded and I expect the user will make multiple API requests without refreshing, and the results will have to be mapped to different components. At the moment, trying to print {items} to the console returns an empty array.

1
  • That is because you are console loggin before you get the response Commented Nov 24, 2020 at 8:27

1 Answer 1

4

Since setItems is the asynchronous method, you can't get the updated value immediately after setItems. You should use another useEffect with dependency to see the value.

useEffect(() => {
  console.log(items);
}, [items]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.