Modify A React Hook Variable Inside UseEffect() That Uses A Fetch() Call
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!
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM