Home>
Stumble

When I access the database with fetch to API and setState, it is not re-rendered.


  {
    (searchResult.data)
       ? searchResult.data.map ((ingredient, i) =>{
         {ingredient.food} 
       })
       :  
     }


function search (e) {
    if (e! =="") {
      fetch (`API something`)
      .then (res =>{
        return res.json ()
      }). then (data =>{
        setSearchResult ({})
        setSearchResult (data)
      })
    }
    setIngredientLoading (false);
  }


(input onChange)

Function onChangeField (e) {
      console.log (e.target.value)
      setSearchWord (e.target.value)
      setIngredientLoading (true)
      search (e.target.value)
    }
Is it useless to use setState in an asynchronous processing function?

I also tried {... data}, but maybe it wasn't deployed enough.
Or it may be due to asynchronous processing.
Please tell me the details.

  • Answer # 1

    This part of the render destination,

         ? searchResult.data.map ((ingredient, i) =>{
             {ingredient.food} 
           })

    For each element of the array called searchResult.data

         (ingredient, i) =>{
             {ingredient.food} 
           }

    I execute the arrow function and make the result into an array, but this function does not return a value.

    Explicitly write a return or

         ? searchResult.data.map ((ingredient, i) =>{
            return  {ingredient.food} 
           })

    {}Delete (or()Changed to)=>I think it's a good idea to have one expression at the end of, instead of a block, so that its value is returned.

         ? searchResult.data.map ((ingredient, i) =>
             {ingredient.food} 
           )
         ? searchResult.data.map ((ingredient, i) =>(
             {ingredient.food} 
           ))

    Reference: Arrow Function --JavaScript | MDN<