Daniel
Daniel

Reputation: 95

cant get redux toolkit to work with async (createAsyncThunk)

Hello stackOverflow friends. I'm starting to use redux toolkit, and there is some stuff that I don't get.

I have this Slice:

const envSlice = createSlice({
  name: "env",
  initialState: { envs: [], loading: false, error: false },
  reducers: {},
  extraReducers: {
    [fetchEnv.pending]: (state) => {
      state.loading = true;
    },
    [fetchEnv.fulfilled]: (state, action) => {
      state.envs = action.payload;
      state.loading = false;
    },
    [fetchEnv.rejected]: (state) => {
      state.loading = false;
      state.error = true;
    },
  },
});

export default envSlice.reducer; 

And I'm trying to fetch some data from a mongo server. this code used to work in the regular redux:

--- fetching all the envs ---

export const fetchEnv = createAsyncThunk("admin/fetchEnv", (thunkAPI) => {
  axios
    .get("http://10.0.0.6:5000/admin/getAllEnv")
    .then((response) => response.data)
    .catch((error) => {
      console.log(error);
      return thunkAPI.RejectWithValue(error);
    });
});

But for some reason its always goes into the catch and rejects - even when this is a response.

this code works:

export const fetchEnv = createAsyncThunk(
  "admin/fetchEnv",
  async (_, thunkAPI) => {
    try {
      const response = await axios.get("http://10.0.0.6:5000/admin/getAllEnv");
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue({ error: error.message });
    }
  }
);

My problem is that I made this work, but I cant understand why the first createAsyncThunk doesn't work, and why the second is working.

To me both functions look kind of the same.

This is an example from RTK docs (for some reason they dont cover error handling in this example, I didn't found one with):

Rtk Docs example

thanks (: .

Upvotes: 2

Views: 3668

Answers (1)

HMR
HMR

Reputation: 39320

From the documentation:

and a callback function that should return a promise

Your async thunk that doesn't work isn't returning anything:

export const fetchEnv = createAsyncThunk("admin/fetchEnv", (thunkAPI) => {
  return axios //<----return a promise
    .get("http://10.0.0.6:5000/admin/getAllEnv")
    .then((response) => response.data)
    .catch((error) => {
      console.log(error);
      return thunkAPI.RejectWithValue(error);
    });
});

Or you can have a bodiless arrow function:

export const fetchEnv = createAsyncThunk(
  'admin/fetchEnv',
  (
    thunkAPI 
  ) => //no { or }
    axios
      .get('http://10.0.0.6:5000/admin/getAllEnv')
      .then((response) => response.data)
      .catch((error) => {
        console.log(error);
        return thunkAPI.RejectWithValue(error);
      })
);

Upvotes: 4

Related Questions