skip to Main Content

I created my store with Redux-Toolkit and my slice. Now wanting to retrieve the data by firebase I created an async thunk by createAsyncThunk. I want to register a user by email and password. The registration is ok, but when I want to register the same user again I cannot capture the errors to display them.

export const signUp  = createAsyncThunk('signUp', async (user) => {
  const {email, password} = user
   
  const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=<KEY VALUE REDACTED>', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ email, password })
  });

  if (!response.ok) {
    console.log("nous")
    throw new Error("Nous avons un problème lors de l'inscription")
  }
    
  const data = response.json()
  return data 
})
const handleSubmit = async () => {
  if (email.length > 0 && password.length > 0) {
    if (isSignUp) {
      setError(null)

      try {
        dispatch(signUp({ email, password }))
      } catch (error) {
        console.log(error)
      }
    } else {
      // alert('Veuillez remplir tous les champs')
    }
  } 
}

2

Answers


  1. just catch error from fetch i.e. change code from

    const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyBzVe7Kti-H852fIzBemumnCYbMODXCIH8', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email,
            password
        })
    });

    to this

      const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyBzVe7Kti-H852fIzBemumnCYbMODXCIH8', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          email:"[email protected]",
          password:"2345dxfcghj"
        })
      }).catch(err=>err)
    Login or Signup to reply.
  2. createAsyncThunk actions always resolve, so there’s a little bit of a refactor you can do to your code to make working with errors better.

    • Surround the asynchronous logic in a try/catch.
    • Wait for the response.json() Promise to resolve.
    • Return a rejection with value. See Handling Thunk Errors.
    • Wait for, and unwrap, the asynchronous action in the UI code. See Handling Thunk Results.
    export const signUp = createAsyncThunk(
      'signUp',
      async (user, thunkApi) => {
        const { email, password } = user;
    
        try {
          const response = await fetch('....', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password })
          });
    
          if (!response.ok) {
            console.log("nous");
            throw new Error("Nous avons un problème lors de l'inscription");
          }
    
          const data = await response.json();
          return data;
        } catch(error) {
          return thunkApi.rejectWithValue(error);
        }
      }
    );
    
    const handleSubmit = async () => {
      if (!email.length || !password.length || !isSignUp) {
        // alert('Veuillez remplir tous les champs')
      }
    
      setError(null);
    
      try {
        const data = await dispatch(signUp({ email, password })).unwrap();
        // Signup was successful
      } catch (error) {
        // Signup failed, handle error
        console.log(error);
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search