简体   繁体   中英

how can i fix 0 arguments, but got 1 problem when using the redux toolkit create actions in reactjs

i've been trying to implement a redux store using redux toolkit in reactjs, but i've been getting this error

Calling this redux#ActionCreator with an argument will return a PayloadAction of type T with a payload of P

Expected 0 arguments, but got 1.

this is my prject slice projectSlice.js where i create my slice, reducer and actions using the redux toolkit

import { createSlice , PayloadAction } from "@reduxjs/toolkit";
export const projectSlice = createSlice({
    name : "project" ,
    initialState : {
        fullProject : {
            selectedProject : null,
            documents : null ,
            collaborators : null ,
            meetings : null ,
            remarks : null ,
            observations : null,
            projectSelected : null,

        }
    
    },
    reducers : {
        addProject : (state , action  ) => {

            state.fullProject.selectedProject = action.payload

        },
        selectFirstProject : (state , action  ) => {

            state.fullProject.projectSelected = action.payload

        }
    }
})


export const {  selectFirstProject } = projectSlice.actions;
export const { addProject } = projectSlice.actions;
export const selectFullProject = (state) => state.project.fullProject;


export default projectSlice.reducer;

and this is how i dispatch the action to redux inside a promise function

 function  promise   ()  {

        // SEND REQUEST TO ADD PROJECT
        axios.post(`http://127.0.0.1:8000/api/v1/projectUpdate` , {
          'id' : project_id ,
          'projectName' : formValues.projectName ,
          'constructionType' : formValues.constructionType ,
          'addresse' : formValues.addresse ,
          'description' : formValues.description ,
          'image_url' : formValues.image_url
        }).then ( result => {

          console.log(result.data.project)
          const temp = result.data.project;
          useDispatch(addProject(temp))
             
        }
        ).catch(error => {
          console.log(error)
        } )
      
      }

You haven't provided a TS type for the action argument in either case reducer. So, by default, RTK's TS types assume that the generated action creator takes no arguments.

You need to do something like (state, action: PayloadAction<SomeTypeHere>) instead:

https://redux.js.org/tutorials/typescript-quick-start#define-slice-state-and-action-types

I'm currently having a similar problem, and I was wondering if you managed to fix it?

  <Formik
        initialValues={initialState}
        validationSchema={validationSchema}
        onSubmit={(values: logInCredentials, formikHelpers: FormikHelpers<logInCredentials>) => {
          try {
            dispatch(setIsLoading(true));
            dispatch(getUserToken(values));
            console.log(`values`, values);
          } catch (error) {
            console.log(error);
          } finally {
            setTimeout(() => {
              dispatch(setIsLoading(false));
              formikHelpers.resetForm();
              formikHelpers.setSubmitting(false);
              navigation.navigate('TabsNavigator');
            }, 750);
          }
        }}> 
...


export const authSlice = createSlice({
  name: 'Auth',
  initialState,
  reducers: {
    setUserToken: (state, { payload }: PayloadAction<AuthTokens>) => {
      state.tokens.token = payload.token;
      state.tokens.refreshToken = payload.refreshToken;
      // state.user.email = payload.message.trim().split(' ')[0];
      if (state.tokens.token) {
        state.isAuthenticated = true;
      }
    },
    setIsLoading: (state, { payload }: PayloadAction<boolean>) => {
      state.isLoading = payload;
    },
    clearAuth: (state) => {
      state.tokens = initialState.tokens;
      state.isAuthenticated = initialState.isAuthenticated;
      state.isLoading = initialState.isLoading;
      state.hasError = initialState.hasError;
      state.errorMessage = initialState.errorMessage;
    },
  },
});

export const { setUserToken, setIsLoading, clearAuth } = authSlice.actions;

export default authSlice.reducer;

export interface logInCredentials {
  email: string;
  password: string;
}

export const getUserToken =
  (values: logInCredentials): Thunk =>
  async (dispatch): Promise<AxiosResponse | AxiosError> => {
    try {
      const { data } = await axiosInstance.post(
        `${API.API_POST_TOKEN_PATH}`,
        {
          email: values.email,
          password: values.password,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );

      axiosInstance.defaults.headers.common = {
        Authorization: `Bearer ${data.token}`,
      };

      dispatch(setUserToken(data));

      return data;
    } catch (error) {
      throw error as AxiosError;
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM