'React js: dependency JSON.stringify(array) does not trigger useEffect
I coded the process of acquiring new access token via refresh token, and sending the new access token to get the data. When I send get request I check if the status code is unauthorized or not, if so,I set unauthorized to true. It triggers the useEffect then it sends the refresh token and gets the access token, and I update the data array. I expect the useEffect to reload one more time as I set the data array as dependency JSON.strigify(data) but it does not trigger reload. Why? My code below:
import Style from '../style/h1.module.css'
import axios from 'axios'
import {useEffect,useState} from 'react'
import style_for_table from '../style/table.module.css'
const List =()=>{
const[data,set_data]=useState([]);
const[unauthorized,set_unauthorized]=useState(false)
useEffect(()=>{
let token=localStorage.getItem('refresh_token')
if(unauthorized){
console.log("expired")
axios.post('http://127.0.0.1:8000/get_refresh_token/',{refresh:token})
.then((response)=>{
localStorage.setItem('access_token',response.data.access) //requesting access if the previous expired
})
}
let config={
headers:{
Authorization: "Bearer"+ " " + localStorage.getItem('access_token')
}
}
axios.get('http://127.0.0.1:8000/products/',config) //requesting data
.then(res=>{
if(res.status !== 401){
set_data(res.data.map(element=>
<tr>
<td>{element.name}</td>
<td>{element.price}</td>
<td>{element.expiration_date}</td>
</tr> ),
)
}
return res
})
.catch((res)=>{
if(res.response.status==401){
console.error("TOKEN EXPIRED AND NEW TOKEN ADDED")
set_unauthorized(true)
}
})
},[unauthorized,JSON.stringify(data)])
return(
<>
<table className={style_for_table.table}>
<tr>
<th>Name</th>
<th>Price</th>
<th>Expiration Date</th>
</tr>
{data}
</table>
</>
)
}
export default List
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
