Home > Net >  Why I can't get the value from map function and use it outside?
Why I can't get the value from map function and use it outside?

Time:11-24

I'm bulding a receipes app for practising, using spoonicular api. I'm stuck trying to display favourites recipes saved on local storage.

I have an array of ids saved in localstorage and Everytime i add a receipe i want to call api and display on screen. To do that I map over the array and get the object but I can't use the data outside map function. here the code thank you if someone can help


const getMyList = () => {

          fav.map(async(id) => {
            try{
              const {data:res} = await axios.get(url)
              return res

              console.log(res)
            } 
            catch(error) {
              console.log(error)
            } 

            })

            setNewArr([...newArr, res])

      }
      useEffect(() => {
          getMyList()
        },[]);

CodePudding user response:

Map is a way to mutate the contents of a array and returns a new array.

const newArray = oldArray.map((item) => item )

CodePudding user response:

const aData = fav.map((id) => axios.get(url)
  .then(r => r.data)
  .catch(e => console.log(e));

Promise.all(aData)
  then((data) => {
    setNewArr(prev => data.reduce((val, item) => ([...val, ...item]), prev));
  });

CodePudding user response:

using Promise.all should help. the function needs to wait for all api calls to finish or updated state when individual response is received

const getMyList = async () => {
    try {
         const promises = fav.map(async(id) => { return axios.get(url)})

         const res = Promise.all(promises)

         const mappedRes = res?.map(r => r.data) ?? []

         setNewArr([...newArr, ...mappedRes ])
     } catch (error) {
          console.error('error fetching, error)
     }
}

More about Promise.all

Hope it helps

CodePudding user response:

try like this

const getMyList = () => {
    let resArray = fav.map(async(id) => {
                try{
                  const res = await axios.get(url)
                  return res.data
    
                  console.log(res)
                } 
                catch(error) {
                  console.log(error)
                } 
    
                })
    
                setNewArr([...newArr, ...resArray])
    
          }
          useEffect(() => {
              getMyList()
            },[]);
  • Related