user2443507
user2443507

Reputation: 393

useState not setting variable

I am confused why useState is not setting the variable from its argument, props.

The fragment is:

import React, { useState } from 'react';

const FormContainer = (props) => {
  console.log('[FormContainer props]', props);   // line 7
  const [prevState, setPrevState] = useState(props);
  console.log('[FormContainer]', prevState);     // line 9

props contains an object but the hook is not setting prevState. It is undefined. Why?

Calling code. The first component presents a list. When a row in the list (grid) is clicked, this component gets the data and sends it as an argument to the second component, FormContainer.

import React, { Component } from 'react';
import Table from './VehicleList';
import VehicleForm from '../FormContainer';

class Vehicles extends Component {
  state = {};

...

  render() {
    return (
      <div>

        {this.state && this.state.vehicleList && (
          <Table vehicleList={this.state.vehicleList} clicked={this.vehicleSelectedHandler} />
        )}
        {console.log('[Vehicles render selectedVehicle]', this.state.selectedVehicle)}
        <VehicleForm vehicle={this.state.selectedVehicle} />
      </div>
    );
  }

From the debugger:

Firefox dev tools

Upvotes: 1

Views: 5031

Answers (1)

UjinT34
UjinT34

Reputation: 4997

useState takes the default value as its argument. It will be set only on the first render and will not update when props change. You should call setPrevState to update the values.

useState is used to access the current state. If you need something for previous props or previous state take a look at the FAQ

It is not a good idea to implement this with hooks. Vehicle state and updating should be inside Vehicles component. There is no need for useState inside a class. VehicleForm should be a stateless component and should receive a callback to update the vehicle.

It would be hard to track changes and handle updates in a generic FormContainer based on the whole props object.

Upvotes: 1

Related Questions