HelloL
HelloL

Reputation: 107

How do I replace this.setState when using React Hooks?

I'm trying to convert my class component to a functional component using React Hooks. I'm not sure what to do with this code snippet:

this.setState({
      pinError: !isValidPin,
      pin: updatedPin,
    });

I was thinking of maybe deleting it completely? This is what I have so far:

const PinInput = ({pinError, pin, isInputActive}) => {

    const handleValidatePinDigit = (e) => {
        const isValidPin = isValidPinDigit(e.target.value);
        const updatedPin = isValidPin ? e.target.value : '';

    this.setState({
      pinError: !isValidPin,
      pin: updatedPin,
    });

    if (get(updatedPin, 'length', '') === 4) {
      onComplete(updatedPin);
    } else {
      onChange(updatedPin);
    }
  };
};

Upvotes: 3

Views: 1460

Answers (4)

Mainly Karma
Mainly Karma

Reputation: 477

This should help you understand how to initialize, set and use state using the useState hook. Please read comments too.

import React, { useState } from 'react';


// pinError & pin are deconstructed state passed down and are used as the initial values of your pinError & pin state
const PinInput = ({pinError, pin}) => {

    const [newPinError, setNewPinError] = useState(pinError); // initialize state
    const [newPin, setNewPin] = useState(pin);

    const handleValidatePinDigit = (e) => {
        const isValidPin = isValidPinDigit(e.target.value);
        const updatedPin = isValidPin ? e.target.value : '';

        setNewPinError(!isValidPin); // set state 
        setNewPin(updatedPin);       
    };

    // this printPin function shows how to use state 
    const printPin = () => {
        if (newPinError) { 
            console.log("[pinError] Your invalid pin is: " + newPin);
        } else {
            console.log("Your valid pin is: " + newPin);
        }
    }
};

Upvotes: 1

Rashed Rahat
Rashed Rahat

Reputation: 2475

Use useState hook to achieve your goal.

Try:

const [pinError, setPinError] = useState(false);
const [pin, setPin] = useState('')

setPinError(!isValidPin)
setPin(updatedPin)

Happy coding :)

Upvotes: 0

BTSM
BTSM

Reputation: 1663

You can't use this.setState function. Try like this.

import React, { useState } from 'react';



const PinInput = ({pinError, pin, isInputActive}) => {

     const [pinError, setPinError] = useState(pinError);
     const [updatedPin, setUpdatedPin] = useState('');
    const handleValidatePinDigit = (e) => {
        const isValidPin = isValidPinDigit(e.target.value);
        const updatedPin = isValidPin ? e.target.value : '';
        setPinError(!isValidPin);
        setUpdatedPin(updatedPin);
    if (get(updatedPin, 'length', '') === 4) {
      onComplete(updatedPin);
    } else {
      onChange(updatedPin);
    }
  };
};

Upvotes: 0

Salman Kazmi
Salman Kazmi

Reputation: 3248

Try this:

 const[pinError, setPinError] = useState(true);
 const[pin, setPin] = useState('')

Upvotes: 0

Related Questions