'Store a global variable from an API

I am trying to validate my JWT cookie from an API using axios from express server. The data is working fine, but how can I store the data comes from an API into redux state? Because it always returns false, but the login system is working great. But I want to validate the token and get the user data so I can use it any where inside the app.

Here is my redux code :

import { createSlice , configureStore, createAsyncThunk } from "@reduxjs/toolkit";
import authService from "./authController";
import axios from "../axios"

const user = document.cookie.split("jwt=")[1];
const datas = null;

export const login = createAsyncThunk(
    "/login",
    async ({ username, password }) => {
        try {
            const {data} = await axios.post(
                "/login",
                {
                    username,
                    password,
                },
                { withCredentials: true }
            ); 
            return { user: data };
        } catch (error) {
            console.log(error);
        }
    }
);


export const checkUser = createAsyncThunk(
    "/check",
    async () => {
            const { data } = await axios.post(
                "/check",
                {},
                {
                    withCredentials: true,
                }
        );
            return {data : data} ;
});


const initialState = user
    ? { isLoggedIn: true, user, datas }
    : { isLoggedIn: false, user: null };


const authSlice = createSlice({
    name: "auth",
    initialState,
    extraReducers: {
        [login.fulfilled]: (state, action) => {
            state.isLoggedIn = true;
            state.user = action.payload.user;
        },
        [checkUser.fulfilled]: (state, action) => {
            state.isLoggedIn = true;
            state.datas = action.payload.data;
        },
        [login.rejected]: (state, action) => {
            state.isLoggedIn = false;
            state.user = null;
        },
    }
    
})

const { reducer } = authSlice;
export default reducer;

what I am trying to do is get the cookie and validate it and then store the user data inside a state. But its not working , how can I store the checkUser data inside a variable to be able to use it any where in the app using useSelector?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source