SkyeBoniwell
SkyeBoniwell

Reputation: 7092

How can I use React Hooks to refresh a table when a row is deleted or added?

I have a react-table component that displays some game data.

The component uses hooks to set state like this:

const [data, setData] = React.useState([]);
React.useEffect(() => {
    gameData(false).then(res => {
        setData(res.data);
    });
}, []);

Inside my table, I have a button that adds or removes a row via a Put request to an api.

I want it to remove the row without doing a full/visable page refresh.

Here is the bit of code that does the axios put request.

You can see I'm trying to use 'setData' again to 'refresh' the data.

But that doesn't work. Now it does remove the row, but I can only see that after I hit f5 or hit the browser refresh button.

const updateGame = async (game, action) => {
    await new Promise(resolve => setTimeout(resolve, 500));

    game.isApproved = action;
    axios({
        method: "PUT",
        url: "api/games/" + game.id,
        data: JSON.stringify(game),
        headers: { 'Content-Type': 'application/json; charset=utf-8' }
    });
    // trying to refresh table after the axios Put request
    setData(data);
};

Is there a way to refresh state dynamically without having to hit refresh?

Thanks!

Upvotes: 2

Views: 6942

Answers (2)

Alvaro Castelan
Alvaro Castelan

Reputation: 251

You have to let the effect know when you want it to run. The empty bracket is basically like using onMount so by adding the data to it will refresh when data is changed.

const [data, setData] = React.useState([]);
React.useEffect(() => {
    gameData(false).then(res => {
        setData(res.data);
    });
}, [data]);

Upvotes: 3

Alex Wayne
Alex Wayne

Reputation: 187014

setData(data);

This just sets the data you already have because the data variable hasn't changed.

Did you mean to set the new data returned by your PUT request? If so you need to await the request, and then set the new state.

You probably want something like:

const newData = await axios({
    method: "PUT",
    url: "api/games/" + game.id,
    data: JSON.stringify(game),
    headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
setData(newData);

Upvotes: 1

Related Questions