Ad

Modify A React Hook Variable Inside UseEffect() That Uses A Fetch() Call

- 1 answer

Inside useEffect(), I am requesting data from a server using a fetch() call.

Upon receipt of the data I am attempting to modify a hook I have defined previously. However, the hook does not want to except this new data.

To make sure that my code is correctly waiting for the data to be returned before transferring this data to my React hook I have set up two variables.

  • The first is an empty array created outside my functional component: “eventTicketInfo”.
  • The second is the hook, also an empty array, created inside my functional component: “ticketInfo”.

My code successfully populates “eventTicketInfo” but not “ticketInfo”.

The response object received from fetch() is an array structured as follows:

[ {ticketID: "fc056", ticketName: "General Admission"},
  {ticketID: "fc057", ticketName: "General Admission + 1 Drink"}
  {ticketID: "fc058", ticketName: "VIP"}
  {ticketID: "fc059", ticketName: "VIP + 1 Drink"} ]

The number of array elements will vary, example above shows four.

But the number of fields inside each array element will remain fixed, example above shows two.

Here is the basic code I am using:

let eventTicketInfo = [];

const EventData = () => {
    const [ticketInfo, setTicketInfo] = useState([]);

    useEffect(() => {
        getEventData(eventID);
    }, []);

    const getEventData = eventId => {
        return fetch(`${API}/event/e/${eventId}`, {method: "GET"})
            .then(response => {
                eventTicketInfo = response;
                setTicketInfo(response);
            })
            .catch(err => {
                console.log(err);
            });
      };
}

This code successfully populates “eventTicketInfo” with an array of four elements. However, “ticketInfo” remains an empty array.

Any help would be appreciated!

Ad

Answer

It seems to work fine when I tried it out: https://codepen.io/LannyIsMyHandle/pen/LYYMZXm

Remember that EventData may render a number of times before the fetch promise resolves and state gets updated, so you should see ticketInfo as an empty array at least once. However, after the state is set, it will re-render the component and you should see actual values.

Ad
source: stackoverflow.com
Ad