I am using recoil for state management, for a very basic todo app for practice, but my todolist.tsx is not showing the updated username and I need to refresh everytime to see the updated username and todos change as soon as the username changes. I can’t figure out the issue.
This is my authState
import { atom } from 'recoil';
export const authState = atom({
key: 'authState',
default: { token: null, username: null },
});
and this is the iniital State
function InitState() {
const setAuth = useSetRecoilState(authState);
const navigate = useNavigate();
const init = async () => {
const token = localStorage.getItem("token");
try {
const response = await fetch('http://localhost:3000/auth/me', {
headers: { Authorization: `Bearer ${token}` }
});
const data = await response.json();
console.log(data);
console.log(data.username);
if (data.username) {
setAuth({ token: data.token, username: data.username });
navigate("/todos");
} else {
navigate("/login");
}
} catch (e) {
navigate("/login");
}
}
useEffect(() => {
init();
}, [])
and inside my todolist.tsx , I am using authStata like this :
const authStateValue = useRecoilValue(authState);
and the username is not updating until I refresh and reload the page, todos fetched are the updated ones but the username is not updating until page is reloaded
return (
<div>
<div style={{ display: "flex" }}>
<h2>Welcome {authStateValue.username}</h2>
<div style={{ marginTop: 25, marginLeft: 20 }}>
<button onClick={() => {
localStorage.removeItem("token");
navigate("/login");
}}>Logout</button>
</div>
</div>
<h2>Todo List</h2>
<input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
<input type="text" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Description" />
<button onClick={addTodo}>Add a new Todo</button>
{todos.map((todo) => (
<div key={todo._id}>
<h3>{todo.title}</h3>
<p>{todo.description}</p>
<button onClick={() => markDone(todo._id)} >{todo.done ? 'Done' : 'Mark as Done'}</button>
</div>
))}
</div>
)
};
export default TodoList
The username should also update as the todolist component re-renders , but except username everythign is fetching is being displayed fine. I can’t figure out the issue, I am just starting out to use typescript with recoil