Error: authorization bearer undefined in the front end. Here is my Here is my code of useEffect of OrderScreen.js `
const dispatch = useDispatch()
const navigate = useNavigate()
const { user } = useSelector((state) => state.auth)
const { orders, isLoading, isError, message } = useSelector(
(state) => state.orders,
)
useEffect(() => {
if (isError) {
toast.error(message)
}
if (!user && !user.isAdmin) {
navigate('/login')
}
dispatch(getOrder())
return () => {
dispatch(reset())
}
}, [user, isError, message, dispatch, navigate])
`
Here is my orderSlice. for the getOrder Function `
const initialState = {
orders: [],
isError: false,
isSuccess: false,
isLoading: false,
message: '',
}
export const getOrder = createAsyncThunk(
'orders/getOrder',
async (_, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token
return await orderService.getOrder(token)
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message)
}
},
)
`
Here is my orderService.js `
const getOrder = async (token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
}
const response = await axios.get(API_URL, config)
return response.data
}
` I tried to solve from these stacks
- Authorization Bearer Token Header in Javascript
- How to send bearer token through header of axios call in react redux
CodePudding user response:
You can try to pass the token as first argument of your thunk function ( currently "_") to make sure it is not undefined. Also, you can use a debugger to know the actual state of the global store (or simply log it in your component).
And lastly, try to log what returns the thunkApi.getState() function.