'Attach Access Token in API call Redux

Im sending id ,accessToken as a parameter to my API, they are redux store states, I want to attach my accessToken in my header.Authorization and send it together with the id of the book. Here's what I've tried

book.js

const { user, isError, message } = useSelector(state => state.auth);

console.log(user.accessToken) /// im getting a token here
dispatch(likeBook(book._id, user.accessToken))
bookSlice.js


export const likeBook = createAsyncThunk('/likebook', async(id, accessToken, thunkAPI) => {

    
    const API = axios.create({ baseURL: 'http://localhost:3000' });

    API.interceptors.request.use((req) => {
  
    req.headers.Authorization = `Bearer ${accessToken}`;
 

    return req;
    });

  
    try {
       
      return await API.patch(`/books/${id}/likeBook`);
              
    } catch (error) {
      const message =
      (error.response && error.response.data && error.response.data.message) ||
      error.message ||
      error.toString()
      return thunkAPI.rejectWithValue(message)
  }

    
})

but in my server when I try reading the header and access token that I sent im getting [object,object] and cant verify the token and getting and error 403

const likeBook = async (req, res) => {

    const authHeader = req.headers.authorization || req.headers.Authorization;
    if (!authHeader?.startsWith('Bearer ')) return res.sendStatus(401);
    const token = authHeader.split(' ')[1];


    console.log(authHeader,token)
    


    jwt.verify(
        token,
        process.env.SECRET,
        (err, decoded) => {
            if (err) return res.sendStatus(403); //invalid token
            _id = decoded.UserInfo._id;
        }
    );
}

Is what im doing here correct? or is there any work around for this, I tried importing my store.js in this file to get the states instead but im getting error Cannot access 'WEBPACK_DEFAULT_EXPORT' before initialization when importing store



Solution 1:[1]

The payload creator you're passing to createAsyncThunk has the wrong signature:

async(id, accessToken, thunkAPI) =>

https://redux-toolkit.js.org/api/createAsyncThunk#payloadcreator will tell you that there's only two arguments, and the second one is the thunk API. Try combining id and accessToken into an object:

async({ id, accessToken }, thunkAPI) =>

Also adjust the place where the thunk is dispatched:

dispatch(likeBook({ id: book._id, accessToken: user.accessToken }))

Also keep in mind that if accessToken is coming from the state itself, you could use the thunkAPI.getState to retrieve it. No need to select it in the component.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 timotgl