I have a react app.
I have an axios component I want to reuse:
JavaScript
x
18
18
1
import axios from 'axios'
2
import dynamic from 'next/dynamic'
3
const baseUrl = 'http://127.0.0.1:8000/'
4
5
const axiosInstance = axios.create({
6
baseURL: baseUrl,
7
timeout: 5000,
8
headers: {
9
Authorization: localStorage.getItem('access_token')
10
? 'Bearer ' + localStorage.getItem('access_token')
11
: null,
12
'Content-Type': 'application/json',
13
accept: 'application/json',
14
}
15
})
16
17
export default axiosInstance
18
Now, I try and import this into my registration page as follows:
import axiosInstance from "axiosInstance"
The file itself looks like this:
JavaScript
1
14
14
1
const handleFormSubmit = async (values: any) => {
2
axiosInstance.post(`account/register/`, {
3
username: values.username,
4
email: values.email,
5
password: values.password,
6
confirm_password: values.confirm_password,
7
}).then((response) => {
8
console.log(response);
9
});
10
11
// router.push('/profile')
12
console.log(values);
13
};
14
However, this throws an error:
Can some please help me with this issue? I am new to Nextjs and looked at
https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
but not sure how to use it in this context.
Advertisement
Answer
localStorage
is a propert on window
object, and since next.js is a server side rendering framework, when next renders the component on server, window.localStorage
will be undefined.
In order to import it, set the axios instance like this:
JavaScript
1
13
13
1
const axiosInstance = axios.create({
2
baseURL: baseUrl,
3
timeout: 5000,
4
headers: {
5
// if localStorage is not defined, it wont throw error
6
Authorization:localStorage && localStorage.getItem('access_token')
7
? 'Bearer ' + localStorage.getItem('access_token')
8
: null,
9
'Content-Type': 'application/json',
10
accept: 'application/json',
11
}
12
})
13
and then inside