Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'reduce' of undefined in react

I have a form in which I am asking the user to input field values for a couple of fields, storing the field values in an state and displaying the state values in a customised format.

So, I have a couple of input fields and a submit button:

<button onClick={this.handleSubmit}>Submit</button>
         {
           this.state.credentials &&
           //<Credentials value={this.state}/>
            <Credentials value={JSON.stringify(this.state, undefined, 2)} />
         }

The Credentials function convert the state of the component in JSON format:

const Credentials = ({value} ) => {
    return <pre>{formatState(value)}</pre>;
}

The formatState function will basically manipulate the state values and display them in the way I want:

function formatState(state) {
  console.log("hi")
  console.log(state);
    const output = state.groups.reduce((final, s)=> {
      console.log(output)
      const values = Object.keys(s).reduce((out, o)=> {
        out[o] = s[o].map(k => Object.values(k))
        return out;
        }, {})
        final =  {...final, ...values}
        return final;
      }, {})
      console.log(output) 
  }

The state looks like this:

{
  "groups": [
    {
      "typeA": [
        {
          "name": "abc"
        },
        {
          "number": "13,14"
        }
      ],
      "typeB": [
        {
          "country": "xyz"
        },
        {
          "date1": "2019-05-14"
        }
      ]
    }
  ]
}

But I want the output like this:

groups: {
"typeA": [[abc],[13,14]],
"typeB": [[2019-05-14],[xyz]]
}

SO, reduce function is used to convert the state into the following output. But I getting the error : "TypeError: Cannot read property 'reduce' of undefined"

Please can anybody tell me why this is happening.

like image 242
user8306074 Avatar asked Oct 27 '22 14:10

user8306074


1 Answers

Error is here <Credentials value={JSON.stringify(this.state, undefined, 2)} />. JSON.stringify produces string representaion of some object (this.state in your case). Argument state of formatState has type of string. It seems that you want to have state arguemnt to be object. So you should do

<Credentials value={this.state} />
like image 109
Fyodor Avatar answered Nov 03 '22 18:11

Fyodor