React multiple http calls when navigating the application using the URL - reactjs

I have a component which has filtering, searching and pagination capabilities. What I'm trying is to create a queryString and attach to the URL such that I can later copy and paste it in another browser so that I can reuse the filters.
To extract the query params from the URL I'm using the useLocation hook
const useQuery = () => new URLSearchParams(useLocation().search);
const pageNo = useQuery().get('page') ?? 1;
I'm using the useEffect hook to track for changes of the page query parameter value, and dispatch an action which will update the pageNo in the state object of my reducer.
React.useEffect(() => {
dispatch({
type: actionDescriptor.CHANGE_PAGE,
payload: pageNo
});
}, [pageNo]);
I have another useEffect hook which handles the fetch of the data, and gets triggered when the pageNo changes. I'm using the useNavigate to create and navigate to the new location if the http call was successful
const nav = useNavigate();
React.useEffect(() => {
(async function get() {
const response = // make http call and get response
if (response.status === 200) {
dispatch({
type: actionDescriptor.FETCH_SUCCESS,
payload: {
data: response.data['value'],
}
});
nav (`/data?page=${state.pageNo}`);
}
/// handle error
}
})();
}, [state.pageNo, state.pageSize, state.filter]);
When I'm navigating using the UI, selecting a different page for example, all works well, there is a single http call, the browser url is updated as expected (e.g. localhost/mydata?page=2). If however I'm copying the url and paste it in another window, it makes two http calls, and renders the dom twice. What might be the cause for this?

my guess is due to the parameters you are listening on state.pageNo, state.pageSize, state.filter. I'm assuming all of these are null/empty at the beginning of your app. Once you copied and pasted the url, two of these parameters will change which will cause the useEffect to be called twice.
put in a console.log in the useEffect to confirm that. Once that's confirmed, I would re-examine the list of parameters to see if you need to listen to all of them.

I would take a look at the pageNo. It looks like it might be changing from default value to 2 since you have 2 useEffects probably firing for the same render.

Related

How to use { useQuery } from react-query while iterating over an array of data

I'm trying to integrate react-query into my React project.
What I have is a custom hook - useBundles which fetches data from a GraphQl endpoint as shown below -
function useBundles() {
const { data, status, isSuccess } = useQuery(
'SaleBundles',
async () => await request(endpoint, gql`query {${saleQuery}}`),
);
return { data, status, isSuccess };
}
I use the return value in my component like this const { data, status, isSuccess } = useBundles(); which works perfectly fine.
Now, what I want to do is, for each item in data I want to call another endpoint (a REST endpoint this time) and I have a seperate async function for that called getData(data: Array) which uses async-await to fetch data from my REST endpoint.
I could just call getData in useBundles passing to it data as an argument. But since getData is async it is required to use await with it (which I can't because I can't define a hook as async).
As an alternative, I tried not to use getData in useBundles but directly call the endpoint using axios like this -
data.forEach((item) => useQuery("some-unique-key", axios.get(<endpoint>)))
This gives me an error saying that useQuery cannot be used in a loop.
I'm kinda stuck at this point as how to proceed. Would appreciate any help. Thanks.
There are basically two ways to solve this:
useQueries
useQueries can be used with a fixed array, but also with a dynamic one, so:
useQueries(data.map(item => ...))
would work. It will give you an array of QueryResults back.
map and create a component
data.map(item => <Item {...item} />
then, you can call useQuery inside the Item component.
Both approaches will yield concurrent requests, the difference is mainly where you have access to the response data: With useQueries, you have access to all of them in your root component. With the second approach, each Item will only have access to its own data. So it just depends on your needs / use-case which version you prefer.

Why is my state not properly rendered in reactjs?

In my project I use ReactJS in combination with redux and firebase.
Creating a thunk to make async calls to firebase and store the data in redux.
When I'm fetching my files from firebase storage.
Using this method:
try {
let list = [];
await storage
.ref()
.child(path)
.listAll()
.then((res) => {
res.items.forEach((item) => {
storage
.ref()
.child(item.fullPath)
.getDownloadURL()
.then((urlRes) => {
list.push({
name: item.name,
url: urlRes,
});
});
});
});
dispatch(getFileActionSuccess(list));
This method works as intended.
It returns an array of files with their url to view/download them.
The problem is when I try to access this object in my state, it returns an empty array.
Even though when checking using Redux Devtools, I can clearly see that after the list was dispatched. And I could see the correct data.
Devtools image
Note: this is not the real code but a representation
function page() {
getFiles();
<filesList/>
}
function filesList() {
const files = useSelector((state) => state.files, _.isEqual);
console.log(files);
return (..insert render..);
}
But when logging the files. It shows an empty array at first. But when expanding it, it shows the correct data. But it doesn't render it. As I don't understand why it isn't showing like it is supposed to I no longer know what to do and how to fix this.
Simply fetch the data on component mount and component update, and update your state accordingly.
If you’re using React Hooks, you can use React.useState() and give it a dependency. In this case the dependency would be the part of your state which will update upon completion of your HTTP request.

How to show loading state only if data is not received yet. Next.js ssr

I have multiple getServerSideProps in my project and I have a header which displays pages and I have to wait for a page to be opened once I click upon it since I need data to be fetched. Once they are fetched the page will be open.
One approach I used to show user a loading state is to use routeChangeStart BUT I stumbled upon one problem and so I would like not to use this case.
If I go on a page and the data is fetching I want to show user a spinner or some indicator and once the data is fetched I want to stop the indicator/spinner.
As you probably figured out, getServerSideProps runs on the server and is blocking. The fetch request needs to complete before the HTML is sent to the user (i.e., the page is changed). So if you want to show a loading indicator, you need to move that fetch request to the client.
For instance, if you probably have a page with this basic structure:
export default function Page({ data }) {
return <div>{data.name}</div>
}
export async function getServerSideProps() {
const response = await fetch('https://example.com/api')
const data = await response.json()
return {
props: { data },
}
}
const fetcher = url => fetch(url).then(res => res.json());
export default function Page() {
const { data } = useSWR('https://example.com/api', fetcher)
if (!data) return <LoadingSpinner />
return <div>{data.name}</div>
}
Or if you don't need SWR and can use a simple fetch request:
export default function Page() {
const [data, setData] = useState()
useEffect(() => {
fetch('https://example.com/api')
.then(async(response) => {
const json = await response.json()
setData(json)
})
})
if (!data) return <LoadingSpinner />
return <div>{data.name}</div>
}
P.S. If the initial fetch request in getServerSideProps used sensitive information (e.g., API secret credentials), then go ahead and setup a Next.js API route to handle the sensitive part and then fetch the new route.
I just used routeChangeStart.
I didn't want to use it since router.push('/map') didn't work in pages/index.tsx file but I solved this issue by creating a new component putting router.push in useeffect and rendering a loader.
routeChangeStart was in _app.js and because of this in index.js router.push() didn't work - I tested it
routeChangeStart - how it works?
When we click on a page the data is being fetched on the server and the page will only be displayed to us once the data is fetched. So we can make the next thing, we can just intercept the route change.
When we click on a link(we wait for data to fetch) we set loading state in routeChangeStart to true and if we moved to another page(it means we fetched the data) we invoke routeChangeComplete which runs once we moved to the route we wanted to, and here we set loading state to false. And after this I just pass the loading state using React Context

My code doesn't fetch data until after a re-render

So i have been trying to fetch data from an API and the link was dependent on a url parameter, but the data is fetched only after a re-render and i cant access them in my render function.
It works on normal pages but when i try to fetch data inside a route depending on a parameter passed with that route, it doesnt work. How could i solve this problem?
NOTE: my fetch is inside a different component with a different file from the one im passing the parameter with
const { name } = useParams();
const [countries, setCountries] = useState([]);
const fetchData = async () => {
const { data } = await axios.get(`https://restcountries.eu/rest/v2/name/${name}`);
setCountries(data);
};
useEffect(() => {
fetchData();
}, []);
Its normal behavior as you and sending an async call to fetch data, and at that time 1st render is called,
To handle this you should add a new state called loading and set it true before calling API and set it false once you got data,
and on bases on loading state, show some loader in ur render method
First of all, you should set dependencies array in your useEffect, so for now, you've set it as empty [], and it means that it will execute only the first render. So, as I understood, you wanna execute ur fetchData function every 'name' params update, so you need to add that param to ur useEffect function, this way:
useEffect(() => {
fetchData();
}, [name]);
Hope I've understood ur request correctly.
I was trying access the fetched data before specifying the index and I didn't use map.

Reload redux on save

I am working on a React.JS project, based on the react-boilerplate templates. Unfortunately, react-boilerplate only has an example of loading remote data into redux. There is no save example.
I was able to write the save actions, reducer and saga, no problem. It is all pretty standard stuff. However, one issue holding me back, which I was unable to resolve - reloading the store after saving.
I did the below:
const mapDispatchToProps = dispatch => {
return {
loadEvent: eventId => dispatch(loadEvent(eventId)),
saveEvent: values => {
const event = dispatch(saveEvent(values))
return dispatch(loadEvent(event.id || values.id))
}
}
}
I want the above code to work as a promise - reload the event by id after save finished to completion.
It is not working like I need it to. I get load invoked, yet there is no new data in the store.
You should create some xxxx_REQUEST and xxxx_SUCCESS|FAILURE action types to each request (not important it is saving or not).
I don't know you are redux-saga or redux-thunk but after your request fetch finished, you should dispatch xxxx_SUCCESS|FAILURE then in your reducer, get data and store it on you store.
Then you could use a selector to get data from redux store in your component.
I resolved this issue by sticking everything inside my saga as below:
try {
// Call our request helper (see 'utils/request')
const createdEvent = yield call(request, requestURL, {
method: !isNaN(id) && id !== undefined && id !== null ? 'PUT' : 'POST',
body: JSON.stringify(event)
})
yield put(eventLoaded(createdEvent, id))
yield put(loadEvent(createdEvent['id']))
} catch (err) {
yield put(eventLoadingError(err))
}
Now, the thing works as I need it to.

Resources