In wordpress I am clicking a search button in front-page.php , that calls a result page . front-page.php loads FrontPage.js , which has this:
localStorage.clear();
localStorage.setItem('flightCardsDataArray', JSON.stringify(flightCardsDataArray));
isDataLoaded();
window.postMessage({ type: 'flightCardsDataLoaded', data: flightCardsDataArray }, '*');
I would like to read this message in App.js , which is React code and this react code insert cards on result page . In App.js I am doing this
window.addEventListener('message', (event) => {
if (event.data && event.data.type === 'flightCardsDataLoaded') {
// Data has been sent from the search page
const data = event.data.data;
console.log('flightCardsDataArray - from app', data);
}
});
but it always gives me data , which is associated with the previous search. I would like to get data for the current search (latest click on search button of front-page.php) .
UPDATE
As per suggestion below , I set the debugger and see that correct iteration of data is passed in flightCardsDataArray when I set it in localstorage, however I am still not able to figure out why App.js shows previously passed data.
My guess is that App.js is reading the message even before the latest click happens , but how do I resolve this? Or is there any other way to approach this?
I changed the approach and made the API call in React itself. So , when the button is clicked in
front-page.php, it goes toresult page.phpwhich is rendered by React . So I made the call to API in React just before rendering hence eliminating the need for event listeners to listen from one page to another to transfer data.The data that needs to be passed from
front-page.phptoresult page.phpand do not require event listeners can still be passed usinglocalStorage.setItemand get it in react using localStorage.getItem . Here is what I am doing in react application which includes fetching and parsing data