简体   繁体   中英

React state still undefined after fetching inside useEffect

In my react app, I am making a request to an API inside useEffect . Once the promise is returned, I am setting state . I then need to use that state to subscribe to a websocket, but state is coming back as undefined so for now I am just logging the state. I only want to do this on initial page load. How can I make an API request, save that information to state, then use that state to do something all on initial page load only?

 const fetchInstruments = () => {
  return axios
    .post('http://localhost:5050/0/public/AssetPairs')
    .then(({ data }) => {
      return data.result
    })
    .catch((error) => console.log(error))
}

function App() {
  const [instruments, setInstruments] = useState()

  useEffect(() => {
    fetchInstruments().then((fetchedInstruments) => {
      setInstruments(fetchedInstruments)
    })
    .then(()=> console.log(instruments)) //this is undefined
  }, [])
}

if I were in your place, I would not use the state to subscribe to a websocket, I will use the result of the HTTP request

checkout this

function App() {
  const [instruments, setInstruments] = useState()

  useEffect(() => {
    fetchInstruments().then((fetchedInstruments) => {
      setInstruments(fetchedInstruments);
      return fetchedInstruments;        // <====== 
    })
    .then((fetchedInstruments) => {
         console.log(fetchedInstruments);
         //TODO : handle websocket subscription 
    }) 
  }, [])
}

You can just make your second API call when you fetched your instruments:

function App() {
  const [instruments, setInstruments] = useState()

  useEffect(() => {
    fetchInstruments().then((fetchedInstruments) => {
      setInstruments(fetchedInstruments)
      secondApiCall(fetchedInstruments); // You can do your second API call here
    })
  }, [])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM