0

I just got started to react so please bear with me. I don't know exactly what I am doing, I'm just picking those things as I go so I'll do my best to walk you through my mental process when building this.

My intentions are to create a registration component, where the backend returns the validation errors in case there are any in form of an object which has following structure.

{
    "username": [
        "A user with that username already exists."
    ],
    "email": [
        "A user is already registered with this e-mail address."
    ]
}

The state manager that I chose to be using is redux, so this comes back every time when the register function is dispatched.

Since it has this structure I wrote a function to help me decompose it and pick up only on the actual errors (the strings).

    const walkNestedObject = (obj, fn) => {
        const values = Object.values(obj)

        values.forEach(val =>
            val && typeof val === "object" ? walkNestedObject(val, fn) : fn(val))
    }

now I want to display them in the view, so I wrote another function which is supposed to do that

    const writeError = (value) => {
        return <Alert message={value} type="error" showIcon />
    }

Down in the actual component I am calling it as this:

{(props.error) ? walkNestedObject(props.error, writeError) : null}

To my surprise if I console.log the value above return in writeError it works flawlessly, every single error gets printed, but none of them gets rendered.

To debug this I've tried multiple variations and none of them seemed to work, I even called the writeError function in the component as

{writeError('test')} 

and it worked for some reason.

At this stage I'm just assuming there's some react knowledge required to fulfil this task that Im just now aware of.

EDIT: A mock example can be found over here Also, I've tried using the first two answers and when mapping through the errors I get this

Unhandled Rejection (TypeError): props.error.map is not a function

with other variations, it mentions the promise from so I'd include how I manage the API request

export const authSignup = (username, email, password1, password2) => dispatch => {
    dispatch(authStart());
    axios.post('http://127.0.0.1:8000/rest-auth/registration/', {
        username: username,
        email: email,
        password1: password1,
        password2: password2
    })
        .then(res => {
            const token = res.data.key;
            const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
            localStorage.setItem('token', token);
            localStorage.setItem('expirationDate', expirationDate);
            dispatch(authSuccess(token));
            dispatch(checkAuthTimeout(3600));
        })
        .catch(err => {
            dispatch(authFail(err.response.data))
        })
}
6
  • 2
    a minimal working example on stackblitz will make it easier to help Apr 10, 2020 at 21:45
  • it looks kinda horrible and I had to improvise the backend response but hopefully you ll get it stackblitz.com/edit/react-ssf6ou?file=Hello.js Apr 10, 2020 at 21:59
  • Where are you using props.error? I can't find it anywhere in your code Apr 10, 2020 at 22:34
  • I get it from redux with mapstatetoprops. Ive taken that away in the mock Apr 10, 2020 at 22:35
  • I'm playing with your stackblitz but I'm really struggling to understand how the errors are collected. I don't see any function that runs on submission of the form or anything...how is your list of errors being created? Apr 10, 2020 at 22:48

2 Answers 2

1

Consider changing the topology of your error messages:

"errors": [
  { "type": "username", "message": "Username already in use." },
  { "type": "email", "message": "Email address already in use."}
]

That makes your implementation a bit easier:

// MyLogin.jsx
import React from 'react'

const MyLogin = () => {
  /**
   * Here we're using state hooks, since it's much simpler than using Redux.
   * Since we don't need this data to be made globally available in our
   * application, it doesn't make sense to use Redux anyway.
   */
  const [errors, setErrors] = React.useState([])

  const handleLogin = (event) => {
    event.preventDefault()
    axios.post('/api/login', formData).then(() => successAction(), (error: any) => {
      setErrors(error) // Update our local state with the server errors
    })
  }

  return (
    <>
      {errors.length && ( // Conditionally render our errors
        errors.map((error) => (
          <Alert type={error.type} message={error.message} />
        )
      )}
      <form onSubmit={handleLogin}>
        <input type='text' name='email' />
        <input type='text' name='username' />
        <input type='password' name='password' />
      </form>
    <>
  )
}

export default MyLogin
0
0

Your walkNestedFunction function checks each layer of an object, and if a given layer of the object is an object itself, it then uses that object to run your function - which in this case is writeError. writeError returns an error <Alert /> as soon as an error arises. But when you stick writeError inside the circular logic of walkNestedFunction, it will hit the first return statement, render it to the page, and then stop rendering. I think this is why you're getting the complete list of errors logged to the console. Your walkNestedFunction continues cycling down through object layers until its done. But in React, only the first return statement will actually render.

A better tactic would be to modify your writeError function to record the erors to a state variable. Then you can render this state variable. Every time the state is updated, the component will rerender with the updated state.

// Define state in your component to contain an array of errors:

state = {
  errors: []
}

// Add an error into state with each iteration of writeError

const writeError = (error) => {
  this.setState({
    errors: [
      ...this.state.errors,
      error
    ]
  })
}


// inside render(), render the state variable containing your errors

<div>
  { this.state.errors.map(error => <p>error</p>) }
</div>

`

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.