Home > other >  Can't seem to update my GET request data, what am I doing wrong
Can't seem to update my GET request data, what am I doing wrong

Time:08-26

I have this function:

const getPlayerData = async (playerId) => {
        await ligaApi.get(`/players/${playerId}`).then((res) => {
            console.log('getPlayerData',res.data);
                 //setPlayers(res.data)? not working
        });

That is getting called inside this function:

const getTeamById = useCallback(async (teamId) => {
    await ligaApi.get(`/teams/${teamId}/players`).then((res) => {
        const response = res.data;
        const getPlayerDataRequests = response?.map((x) => x.playerId);

        Promise.all(getPlayerDataRequests).then((res) => {
            console.log('RES',res)
            
            for (let i = 0; i < res.length; i  ) {
                const playerData = res[i];
            --> getPlayerData(playerData);
            
            }
        });
    });
}, []);

So in my GET request, I get 3 different object arrays.

{ id: 1373, firstName: 'homer', lastName: 'simpson', email: '[email protected]', run: '1235457', …}
    {id: 1595, firstName: 'Jebediah', lastName: 'Springfield', email: '[email protected]', run: '11111111-1', …}
    {id: 4002, firstName: 'Jugador', lastName: 'De Prueba', email: '[email protected]', run: '5405844-6', …}

The thing is I want to update the state:

const [players, setPlayers] = useState([]);

And when I update the state inside getPlayerData my Web page breaks. My end goal is to map the info through a card list component passing the state as prop but can't seem to get it.

CodePudding user response:

You've wrapped Promise.all() around the wrong set of data.

After retrieving the array of player IDs, you should map the IDs to an array of promises, ie the results from getPlayerData(playerId). Then you can use Promise.all() to wait for those to resolve

// define these outside your component rather than using `useCallback`
const getPlayerData = async (playerId) =>
  (await ligaApi.get(`/players/${playerId}`)).data;

export const getTeamById = async (teamId) => {
  const { data } = await ligaApi.get(`/teams/${teamId}/players`);
  return Promise.all(data.map(({ playerId }) => getPlayerData(playerId)));
};

Then in your component, you can simply use this in an effect hook

getTeamById(teamId).then(setPlayers).catch(console.error);

CodePudding user response:

I ended up updating state like this:

setPlayers((prevState)=>[...prevState, response]);

So thank you Skar, I could understant better

CodePudding user response:

Try the spread operator as mentioned in this post for arrays in useState: useState on React Hooks not updating Array

  • Related