How to get session data in next-auth after loading is done - reactjs

I am trying to get data using useSession, and this data I store in my state, but when I get data using this, it returns me null object since data is still in loading state.
Is there any way I can get data only after status is not loading and till then block the page?
const { data: session, status } = useSession();
useEffect(() => {
const { data } = getCookieData(session);
if (data) setUser(() => data.user);
}, []);

Comment turned into an answer:
useSession changes the state after the status changes. If you want the code inside the useEffect to run after state changes, you probably want to put that state inside the brackets, so this code:
useEffect(() => {
const { data } = getCookieData(session);
if (data) setUser(() => data.user);
}, []);
Would become this
useEffect(() => {
const { data } = getCookieData(session);
if (data) setUser(() => data.user);
}, [data,status]);
And in general whenever you need to trigger some function every time a particular prop or state changes you should place those variables inside the useEffect()
More info about useEffect and lifecycles in the docs:
https://reactjs.org/docs/hooks-effect.html

Related

My custom React hook method "useFetch" is running 8 times when called

Hope anyone is able to help me with a custom react hook.
My custom react hook "useFetch" is running 8 times when called.
Can anyone see, why it is running 8 times when the custom "useFetch" hook is called?
I am a bit new to React, but it seems like I am using useEffect method wrong. Or maybe I need to use another method.
UseFetch hook method:
import React, { useState, useEffect } from "react";
export const useFetch = function (
options = {
IsPending: true,
},
data = {}
) {
// load data
const [loadData, setLoadData] = useState(null);
// pending
const [isPending, setIsPending] = useState(false);
// error
const [isError, setIsError] = useState(false);
useEffect(() => {
// method
const fetchData = async function () {
// try
try {
// set pending
setIsPending(true);
// response
const response = await fetch(data.url, data);
// handle errors
if (response.status !== 200 && response.status !== 201) {
// throw new error with returned error messages
throw new Error(`Unable to fetch. ${response.statusText}`);
}
// convert to json
const json = await response.json();
// set load data
setLoadData(json);
// set error
setIsError(false);
// set pending
setIsPending(false);
// catch errors
} catch (err) {
// set error
setIsError(`Error fetching data: ${err.message}`);
// set pending
setIsPending(false);
}
};
// invoke fetch data method
fetchData();
}, []);
// return
return {
loadData,
isPending,
isError,
};
};
export default useFetch;
Everytime you change a state in a hook, the component that has the hook in it will rerender, making it call the function again.
So let's start counting the renders/rerenders by the change of state:
Component mounted
setIsPending(true)
setLoadData(json)
setIsPending(false)
(depending if it's successful or not you might get more state changes, and therefore rerenders, and therefore hook being called again)
So 4 is not 8, so why are you getting 8?
I presume you are using React18, and React18 on development and StrictMode will call your useEffect hooks twice on mount: React Hooks: useEffect() is called twice even if an empty array is used as an argument
What can you do to avoid this?
First of all, check on the network tab how many times you are actually fetching the data, I presume is not more than 2.
But even so you probably don't want to fetch the data 2 times, even though this behaviour won't be on production and will only be on development. For this we can use the useEffect cleanup function + a ref.
const hasDataFetched = useRef(false);
useEffect(() => {
// check if data has been fetched
if (!hasDataFetched.current) {
const fetchData = async function () {
// fetch data logic in here
};
fetchData();
}
// cleanup function
return () => {
// set has data fetched to true
hasDataFetched.current = true;
};
}, []);
Or as you suggested, we can also add data to the dependency array. Adding a variable to a dependency array means the useEffect will only be triggered again, when the value of the variable inside the dependency array has changed.
(Noting that data is the argument you pass to the useFetch hook and not the actual data you get from the fetch, maybe think about renaming this property to something more clear).
useEffect(() => {
// check if data has been fetched
const fetchData = async function () {
// fetch data logic in here
};
fetchData();
}, [data]);
This will make it so, that only if loadData has not been fetched, then it will fetch it. This will make it so that you only have 4 rerenders and 1 fetch.
(There is a good guide on useEffect on the React18 Docs: https://beta.reactjs.org/learn/synchronizing-with-effects)
Every time you change the state within the hook, the parent component that calls the hooks will re-render, which will cause the hook to run again. Now, the empty array in your useEffect dependency should be preventing the logic of the hook from getting called again, but the hook itself will run.

How to properly re-render functional component after API call

When the page loads, I am making an API call, displaying a table with appointments. After the API call, I set a state for hasData to true, and the data is inserted in another setState. The issue is when the API returns the data from the async call, the component does not show the data. Please see code below.
const [recentAppointmentData, setRecentAppointmentData] = useState([])
const [hasAppointmentData, setHasAppointmentData] = useState(false)
const getAppointments = useCallback(() => {
const getAppointmentDataService = new GetAppointmentsService();
getAppointmentDataService.getDataFromService("263749804").then((results) => {
console.log("APPOINTMENT DATA ", results);
results.recentAppointments.map((result) => {
var recentAppointments = {
appointmentObject: {
serviceCategory: [],
serviceId: "",
appointmentDate: "",
groomer: "",
resourceId: "",
visitId: "",
},
};
if (result["services"] !== undefined) {
console.log("SERVICESS", result["services"]);
result["services"].map((service) => {
recentAppointments.appointmentObject.serviceCategory.push(
service["serviceCategory"]
);
recentAppointments.appointmentObject.serviceId = service["serviceId"];
});
}
recentAppointments.appointmentObject.appointmentDate = moment(
result["appointmentDateTime"]
).format("MM/DD/YY");
recentAppointments.appointmentObject.groomer = result["groomer"];
recentAppointments.appointmentObject.resourceId = result["resourceId"];
recentAppointments.appointmentObject.visitId = result["visitId"];
appointments.push(recentAppointments.appointmentObject);
Here I am setting the has Appointment data to true after the async function has been completed.
if (!hasAppointmentData) {
setHasAppointmentData(true);
}
});
Here I am storing the data in another state.
if (!hasAppointmentData) {
console.log("APPOINTMEN", appointments);
setRecentAppointmentData(appointments);
}
});
}, [hasAppointmentData]);
I am calling the function in the useEffect.
useEffect(() => {
getAppointments();
renderTabs();
}, [getAppointments, renderTabs]);
Can someone guide me on what I am doing wrong? Thanks
The problem is that you're using the useEffect hook wrong.
useEffect runs every time one of its dependencies change, or runs just once when the component mounts if you don't pass in any dependency to it. The dependencies are usually state variables within the component that useEffect runs in.
You want your getAppointments() to run only once, since it calls an external API to get the data. And you want to call renderTabs() (which I assume is responsible for displaying the data in the UI) only when the data is available. So you need to put them into two separate useEffect hooks.
useEffect(() => {
getAppointments();
}, []); // Runs just once when the component is mounted
useEffect(() => {
if (hasAppointmentData) {
renderTabs();
}
}, [hasAppointmentData]); // Runs every time the value of hasAppointmentData changes
But you'll need to watch out for a problem here, when using hasAppointmentData as the dependency. You're calling setHasAppointmentData first, and then following it up with setRecentAppointmentData. The second useEffect hook would run right after you set the boolean to true. By the time renderTabs() tries to fetch the data from recentAppointmentData, the data may not have been updated.
To me, hasAppointmentData is pretty much useless here. Checking for recentAppointmentData.length would serve you just as well, and is guaranteed to work reliably every time. So my second hook would look like this:
useEffect(() => {
if (recentAppointmentData.length) {
renderTabs();
}
}, [recentAppointmentData.length]);

How to call api inside of a loop and perform action on it inside of useEffect React Native

Here is my scenario:
I'm having a cart object in Redux store having information in the form of array of objects having sellerId and the array of products, and I want to map on each object to get sellerId and then fetch seller's data from API on page load.
Here's my code
const [uniqueSellers, setUniqueSellers] = useState([]);
useEffect(() => {
const uniqueSellerIds = [];
cart.filter((item) => {
if (!uniqueSellerIds.includes(item.sellerId)) {
uniqueSellerIds.push(item.sellerId);
}
});
if (uniqueSellerIds.length === 1) setItems(["Seller's delivery"]);
uniqueSellerIds.map((sellerId) =>
axios.get(`${devBaseURL}/sellers/${sellerId}`).then((res) => {
setUniqueSellers((prev) => [
...prev,
{
sellerId: res.data.data[0]._id,
sellerProvince: res.data.data[0].businessAddress.province,
},
]);
}),
);
// Here I want to perform some operations on uniqueSellers state, but it's not available here
console.log('uniqueSellers: ', uniqueSellers); // logs empty array
setLoading(false);
return () => {
setUniqueSellers([]);
};
}, []);
Mutating state is an async process. Fetch operations are also async. So, your console log always executes before your axios call and setUniqueSellers hook.
Listen changes in uniqueSellers array inside another useEffect by giving it as a dependency.
useEffect(() => {
console.log(uniqueSellers); //will log after every change in uniqueSellers
}, [uniqueSellers])

Using useEffect properly when making reqs to a server

I have a handleRating function which sets some state as so:
const handleRating = (value) => {
setCompanyClone({
...companyClone,
prevRating: [...companyClone.prevRating, { user, rating: value }]
});
setTimeout(() => {
handleClickOpen();
}, 600);
};
I think also have a function which patches a server with the new companyClone values as such:
const updateServer = async () => {
const res = await axios.put(
`http://localhost:3000/companies/${companyClone.id}`,
companyClone
);
console.log("RES", res.data);
};
my updateServer function gets called in a useEffect. But I only want the function to run after the state has been updated. I am seeing my res.data console.log when I load my page. Which i dont want to be making reqs to my server until the comapanyClone.prevRating array updates.
my useEffect :
useEffect(() => {
updateServer();
}, [companyClone.prevRating]);
how can I not run this function on pageload. but only when companyClone.prevRating updates?
For preventing function call on first render, you can use useRef hook, which persists data through rerender.
Note: useEffect does not provide the leverage to check the current updated data with the previous data like didComponentMount do, so used this way
Here is the code example.
https://codesandbox.io/s/strange-matan-k5i3c?file=/src/App.js

Prevent infinite renders when updating state variable inside useEffect hook with data fetched using useQuery of graphql

Graphql provides useQuery hook to fetch data. It will get called whenever the component re-renders.
//mocking useQuery hook of graphql, which updates the data variable
const data = useQuery(false);
I am using useEffect hook to control how many times should "useQuery" be called.
What I want to do is whenever I receive the data from useQuery, I want to perform some operation on the data and set it to another state variable "stateOfValue" which is a nested object data. So this has to be done inside the useEffect hook.
Hence I need to add my stateOfValue and "data" (this has my API data) variable as a dependencies to the useEffect hook.
const [stateOfValue, setStateOfValue] = useState({
name: "jack",
options: []
});
const someOperation = (currentState) => {
return {
...currentState,
options: [1, 2, 3]
};
}
useEffect(() => {
if (data) {
let newValue = someOperation(stateOfValue);
setStateOfValue(newValue);
}
}, [data, stateOfValue]);
Basically I am adding all the variables which are being used inside my useEffect as a dependency because that is the right way to do according to Dan Abramov.
Now, according to react, state updates must be done without mutations to I am creating a new object every time I need to update the state. But with setting a new state variable object, my component gets re-rendered, causing an infinite renders.
How to go about implementing it in such a manner that I pass in all the variables to my dependency array of useEffect, and having it execute useEffect only once.
Please note: it works if I don't add stateOfValue variable to dependencies, but that would be lying to react.
Here is the reproduced link.
I think you misunderstood
what you want to be in dependencies array is [data, setStateOfValue] not [data, stateOfValue]. because you use setStateOfValue not stateOfValue inside useEffect
The proper one is:
const [stateOfValue, setStateOfValue] = useState({
name: "jack",
options: []
});
const someOperation = useCallback((prevValue) => {
return {
...prevValue,
options: [1, 2, 3]
};
},[])
useEffect(() => {
if (data) {
setStateOfValue(prevValue => {
let newValue = someOperation(prevValue);
return newValue
});
}
}, [data, setStateOfValue,someOperation]);
If you want to set state in an effect you can do the following:
const data = useQuery(query);
const [stateOfValue, setStateOfValue] = useState({});
const someOperation = useCallback(
() =>
setStateOfValue((current) => ({ ...current, data })),
[data]
);
useEffect(() => someOperation(), [someOperation]);
Every time data changes the function SomeOperation is re created and causes the effect to run. At some point data is loaded or there is an error and data is not re created again causing someOperation not to be created again and the effect not to run again.
First I'd question if you need to store stateOfValue as state. If not (eg it won't be edited by anything else) you could potentially use the useMemo hook instead
const myComputedValue = useMemo(() => someOperation(data), [data]);
Now myComputedValue will be the result of someOperation, but it will only re-run when data changes
If it's necessary to store it as state you might be able to use the onCompleted option in useQuery
const data = useQuery(query, {
onCompleted: response => {
let newValue = someOperation();
setStateOfValue(newValue);
}
)

Resources