How to Initialize Redux Store asynchronously?

60 views Asked by At

I have a Next.js Application and for State Management I am using Redux Toolkit. Now, to maintain authentication status in frontend side, I need to take the existing token and send it to backend for validation. If I get a success Response from backend then I want to initialize my Redux store with {isAuthenticated: true} else {}. How would I achieve such thing.

I have explored other options but Nothing seem to provide satisfying and efficient answer.

1

There are 1 answers

3
fati seddigh On BEST ANSWER
// Redux Slice - authSlice.js
import { createSlice } from '@reduxjs/toolkit';

export const authSlice = createSlice({
  name: 'auth',
  initialState: {
    isAuthenticated: false,
  },
  reducers: {
    setAuthenticated: (state) => {
      state.isAuthenticated = true;
    },
    setUnauthenticated: (state) => {
      state.isAuthenticated = false;
    },
  },
});

export const { setAuthenticated, setUnauthenticated } = authSlice.actions;

// Async action for validating token
export const validateToken = (token) => async (dispatch) => {
  try {
    // Make an API call to the backend with the token
    const response = await fetch('/validate-token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ token }),
    });

    // Check the response
    if (response.ok) {
      dispatch(setAuthenticated());
    } else {
      dispatch(setUnauthenticated());
    }
  } catch (error) {
    // Handle error if needed
    console.error('Error validating token:', error);
    dispatch(setUnauthenticated());
  }
};

export default authSlice.reducer;