简体   繁体   中英

React JS useState initial value not updating inside JS fetch API

I am novice to React JS. I have useState and fetchAPI inside contextAPI hooks but the initial state is not updating.

// code

import React,{useState, createContext} from 'react'


export const contextApi = createContext()

export const ContextApiProvider = (props) => {

    
const [query, setQuery] = useState('chicken')
const [recipes, setRecipes] = useState([])

const api_props = {
    APP_ID: '84cf712e',
    APP_KEY:'asdcb2b8b842f3e543casjakfa710de4fb343592a64d',
    APP_QUERY: query
  }
  
 fetch(`https://api.edamam.com/search?q=${api_props.APP_QUERY}&app_id=${api_props.APP_ID}&app_key=${api_props.APP_KEY}`)
.then(res => res.json()).then(data => setRecipes(data.hits))


    return (
        <contextApi.Provider value={{recipes}}>
            {props.children}
        </contextApi.Provider>
    )
}

First look up the useEffect hook that is where you want to do your data fetching. From there you could set the state using the setState hook that you are running. This might create an endless loop because your are setting state which reruns the component which then trys to set state again.

Hope that helps let me know if you have questions.

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