Inside of Redux toolkit thunk I'm making axios call to server and recieve data of type IToken. I also created axiosClient and user function. Problem is with typescript. When I make axios call inside of thunk instead of putting it in seperate file all works as intendead. Other then that error code is operational. Axios Client I took from another perfactly working project with same functionality, and I wasn`t touching that code - so I couldnt broke it.
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios'
import { signup } from '../../api/users';
import { IToken } from '../../types/IToken';
import { IRegister } from '../../types/IRegister';
type InitialState = {
user: IToken | null;
status:'idle' | 'failed' | 'pending' | 'fullfilled';
error: string | null;
};
const initialState: InitialState = {
user: null,
status: 'idle',
error: null,
};
export const registerUser = createAsyncThunk('user/registerUser', async (data: IRegister, thunkAPI) => {
try {
return await signup(data);
} catch (err ) {
if (axios.isAxiosError(err)) {
if (
err.response
&& err.response.data
&& err.response.data.error
) {
return thunkAPI.rejectWithValue(err.response.data.error);
} else {
return thunkAPI.rejectWithValue(err.message);
}
}
}
});
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
logOutUser: (state) => {
state.user = null;
state.error = null;
state.status = 'idle';
},
},
extraReducers(builder) {
builder
.addCase(registerUser.pending, (state) => {
state.error = null;
state.status = 'pending';
state.user = null;
})
.addCase(registerUser.fulfilled, (state, action) => {
state.status = 'fullfilled';
state.error = null;
state.user = action.payload;
})
.addCase(registerUser.rejected, (state, action ) => {
if (typeof action.payload === 'string') {
state.error = action.payload;
}else {
state.error = 'error';
}
state.status = 'failed';
state.user = null;
});
},
});
export const { logOutUser } = userSlice.actions;
export default userSlice.reducer;
I have an error:
here is axiosClient with function
import { client } from './axiosClient';
import { IRegister } from '../types/IRegister';
import { IToken } from '../types/IToken';
export const signup = (post: IRegister) => {
return client.post<IToken>('/user/signup', post);
};
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:8000/api',
headers: {
Accept: `application/json`,
},
});
export const client = {
async get<T>(url: string) {
const response = await instance.get<T>(url);
return response.data;
},
async post<T>(url: string, data: any) {
console.log(url, data);
const response = await instance.post<T>(url, data);
return response.data;
},
async patch<T>(url: string, data: any) {
const response = await instance.patch<T>(url, data);
return response.data;
},
async delete(url: string) {
return instance.delete(url);
},
};