useSWR not picking updated state variable - reactjs

The token variable is not updating in SWR as I update it via useState in revalidate function.
const [token, setToken] = useState('')
console.log(token) // this updates as setToken is called
const fetcher = (url) => {
console.log(token) // this remains empty although it re-renders
return axios.get(
url,
{
headers: {
'Authorization': `Bearer ${token}`,
},
},
)
.then(res => res.data)
.catch(error => {//whatever})
}
const { data: user, error, revalidate } = useSWR('_ENDPOINT_', fetcher)
const login = (email, password) => {
axios.post('/login', {email, password})
.then((response) => {
setToken(response.data.token)
revalidate()
})
}

I end up using:
'Authorization': `Bearer ${localStorage.getItem('_token').
replace(/['"]+/g, '')}`,
'Authorization': `Bearer ${token}` // instead of this using from useState which didn't update in ages
Because it appears localStorage was available after useSWR init; (even on page refreshes)

You have to use useCallback on the fetcher function for it to properly pick up the token state variable change.
const fetcher = useCallback(
(url) => {
console.log(token) // Will log the updated `token` value
return axios
.get(
url,
{ headers: { 'Authorization': `Bearer ${token}` } }
)
.then(res => res.data)
.catch(error => {/*whatever*/})
},
[token]
)
A better solution, to avoid using useCallback, would be to move the fetcher function outside the component, and pass several arguments to the fetcher in the useSWR call. This has the benefit of using the token as the key for the request (in addition to the URL, making the caching more specific), and only making the request when token is defined.
const fetcher = (url, token) => {
return axios
.get(
url,
{ headers: { 'Authorization': `Bearer ${token}` } }
)
.then(res => res.data)
.catch(error => {/*whatever*/})
}
const SomeComponent = () => {
const [token, setToken] = useState('')
const { data: user, error, revalidate } = useSWR(token ? ['_ENDPOINT_', token] : null, fetcher)
// Rest of the component
}

Related

Infinite rendering of component while fetching data with useEffect hook in reactjs

When i want to fetch collections from api, infinite rendering in useEffect happening on the console. How can fix it?
const Collections = () => {
const [collections, setCollections] = useState([]);
const token = window.localStorage.getItem("token");
useEffect(() => {
fetchUsers();
},[setCollections]);
const fetchUsers = async () => {
const response = await fetch(
"https://itransition-capstone.herokuapp.com/collections/allCollections",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
}
);
const data = await response.json();
setCollections(data);
console.log("Collections", data);
};
};
export default Collections;

Not able to implement data from one api used to get data from another

I am making a meme sharing app. In that app there are total 2 apis of getting memes.
One for memes by all the users another is only for individual user.
In second api I am able to get the data as the user id is from 3rd api.
from here i get the id of each individual.
function UserProfile({memeid}) {
const token = localStorage.getItem("token");
const [response, setResponse] = useState({});
const [id, setId] = useState('')
const userData = async() => {
await axios
.get("http://localhost:8081/userInfo/me", {
headers: { Authorization: `Bearer ${token}` },
Accept: "application/json",
"Content-Type": "application/json",
})
.then((res) => {
setResponse(res.data)
setId(res.data.id)
memeid = id
})
.catch((err)=>{
console.log(err)
})
}
console.log(id)
useEffect(()=>{
userData()
},[])
Now I want this to be used in in another api. for that is have written this code.
function MemeById({id}) {
const [response, setResponse] = useState([])
const token = localStorage.getItem("token");
// const id = "632a119672ba0e4324b18c7d"
const memes = async () => {
await axios
.get("http://localhost:8081/memes/" + id, {
headers: { Authorization: `Bearer ${token}` },
Accept: "application/json",
"Content-Type": "application/json",
})
.then((res) => {
const data = res.data;
setResponse(res.data)
console.log(data);
})
.catch((err) => {
alert(err);
console.log(err);
});
};
useEffect(()=>{
memes()
},[])
I am calling these two at User
function User() {
let id;
return (
<div>
<UserProfile memeid={id}/>
<MemeById id = {id} />
</div>
)
}
I am getting the error for this.
How to solve this error
You're making a big mistake. I think you should learn more about state and props in react.
Problem :
In your User component, you're creating a variable and passing that variable into two other component. You're trying to update the value of props from UserProfile and expecting that updated value in MemeById which is not going to work.
Solution :
function User() {
const [memeId, setMemeId] = useState(null);
return (
<div>
<UserProfile updateId={(newId) => setMemeId(newId)}/>
<MemeById memeId = {memeId} />
</div>
)
}
And in your UserProfile component
function UserProfile({updateId}) {
...
const userData = async() => {
...
// memeid = id
updateId(res.data.id)
...
}
In you MemeById component:
function MemeById({memeId}) {
...
// use memeId here
...
}

Using Axios in useEffect from an external file

I'm trying to export an axios call from an external file to my component, in useEffect. Im exporting the function and importing in the said component. The response is "undefined".
api_call.js:
import axios from 'axios';
const accessToken = window.localStorage.getItem('accessToken')
export const getPublicCircles = async () => {
const headers = {
'Content-Type': 'application/json',
'Accept-Language': 'fr',
'Authorization': `Bearer ${accessToken}`,
}
await axios.get('https://myurl.com/api/this-info', { headers })
.then(response => console.log(response))
.catch(error => console.log('error', error))
};
( I also tried with .then((response) => return response.data.data)
component.js
import * as API from '../../api/api_call';
export default function PublicCircles() {
const [circles, getCircles] = useState('');
useEffect(() => {
const fetchData = async () => {
const response = await API.getPublicCircles();
const json = await response.json();
console.log(response)
getCircles(response);
}
fetchData()
.catch(console.error);;
}, []);
return (
<Box>
{circles === '' ? null :
<PublicCircle circles={circles} />}
</Box>
)
}
Here are the results (getting the info from the api_call.js file, not the PublicCirlces.js one.
Thank you.
The real problem here is that the function getPublicCircles returns nothing, which is why any variable to which the result of this function call is assigned as a value, will be undefined per JavaScript rules, because a function that doesn't return any value will return undefined.
It's not a good idea to use async/await and then/catch in handling a promise together. Below is the example of handling it correctly with try/catch and async/await:
export const getPublicCircles = async () => {
const headers = {
'Content-Type': 'application/json',
'Accept-Language': 'fr',
'Authorization': `Bearer ${accessToken}`,
}
try {
const data = await axios.get('https://myurl.com/api/this-info', { headers });
return data;
} catch(error) {
console.error('error',error);
}
}

Why I need to refresh manually to fetch data api in react?

I make react app using react router v5, and axios as api instance. I fetch the data in AppRouter file.
Here is my approuter.tsx
const AppRouter = () => {
const dispatch = useAppDispatch();
const token = useAppSelector((state) => state.user.token);
const getUser = useCallback(async () => {
const { data } = await Services.getUser();
dispatch(userAction.setUser(data));
}, [dispatch]);
useEffect(() => {
const localStorage = new LocalStorageWorker();
const storageToken = localStorage.get('token');
dispatch(userAction.setToken(storageToken));
}, [dispatch]);
useEffect(() => {
if (token) {
getUser();
console.log('Worked');
}
}, [token, getUser]);
return (
...
)
}
Actually the function work properly, but I need to refresh the page manually to run these functions. How can I make the function run without refreshing the page?
Update:
The problem is because my axios create instance. I should use interceptors to keep the data fetching in useEffect.
My instance looks like this:
(before update)
const token = localStorage.get('token');
const createInstance = () => {
const instance = axios.create({
baseURL: BASE_URL,
headers: {
'content-type': 'application/json',
Accept: 'application/json',
},
});
instance.defaults.headers.common.Authorization = `Bearer ${token}`;
return instance;
};
(after update)
const createInstance = () => {
const instance = axios.create({
baseURL: BASE_URL,
headers: {
'content-type': 'application/json',
Accept: 'application/json',
},
});
instance.interceptors.request.use(
(config) => {
const token = window.localStorage.getItem('token');
if (token) {
return {
...config,
headers: { Authorization: `Bearer ${token}` },
};
}
return null;
},
(err) => Promise.reject(err)
);
return instance;
};
And now the data fetching is work properly. Thank you

How to create a global 401 unauthroized handler using React + ReactQuery + Axios stack?

So I architected frontend in the way which encapsulates every API operation tied to a single resource inside custom hook like this:
export default function useSubjects() {
const queryClient: QueryClient = useQueryClient();
const token: string | null = useStore((state) => state.user.token);
const { yearCourseId } = useParams<{ yearCourseId: string }>();
const getSubjects = async () => {
const response = await axios.get(`yearCourses/${yearCourseId}/subjects`, {
headers: { Authorization: `Bearer ${token}` },
});
return response.data;
};
const postSubject = async (subject: SubjectType) => {
const response = await axios.post(`yearCourses/${yearCourseId}/subjects`, subject, {
headers: { Authorization: `Bearer ${token}` },
});
return response.data;
};
const query = useQuery(SUBJECTS_QUERY_KEY, getSubjects);
const postMutation = useMutation(postSubject, {
onSuccess: (subject: SubjectType) => {
queryClient.setQueryData(SUBJECTS_QUERY_KEY, (old: any) => [...old, subject]);
},
});
return { query, postMutation };
}
Now what is the way to globally handle 401 unauthorized? I would like to navigate user to /login on every unauthorized request. Note that I have more hooks like this tied to other resources.
use the onError callback. You can also do this globally as a callback on the queryCache
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: error => {
// check for 401 and redirect here
}
})
})

Resources