Search code examples
reactjstypescriptredux-toolkit

Argument of type 'string | null' is not assignable to parameter of type 'string'


enter image description here about code have a error is "Argument of type 'string | null' is not assignable to parameter of type 'string'."

the function defined is:

export const getShoppingCart = createAsyncThunk(
  "shoppingCart/getShoppingCart",
  async (jwt: string, thunkAPI) => {
    const { data } = await axios.get(
      `https://e9e0fde5-0f50-4037-af58-6b187be97f69.mock.pstmn.io/shoppingCart`,
      {
        headers: {
          Authorization: `bearer ${jwt}`,
        },
      }
    );
    return data.shoppingCartItems;
  }
);

The store type is:

interface ShoppingCartState {
  loading: boolean;
  error: string | null;
  items: any[];
}

const initialState: ShoppingCartState = {
  loading: true,
  error: null,
  items: [],
};
The slice is:

export const shoppingCartSlice = createSlice({
  name: "shoppingCart",
  initialState,
  reducers: {},
  extraReducers: {
    [getShoppingCart.pending.type]: (state) => {
      state.loading = true;
    },
    [getShoppingCart.fulfilled.type]: (state, action) => {
      state.items = action.payload;
      state.loading = false;
      state.error = null;
    },
    [getShoppingCart.rejected.type]: (
      state,
      action: PayloadAction<string | null>
    ) => {
      state.loading = false;
      state.error = action.payload;
    }
   }
  })

My question is whether there is a more standardised solution to it? I am learning about it. Thanks!

I can fix it by Ternary Operators. like this:

useEffect(() => {
    dispatch(getShoppingCart(jwt ? jwt : ''))
  }, [jwt, dispatch])


Solution

  • 'string | null' is not assignable to parameter of type 'string'

    Because user.token is string | null you cannot use it for getShoppingCart (which expects string)

    Fix

    If you are sure its not null you can use a non null assertion i.e. getShoppingCart(jwt!)

    More