M
M
MrYogurt2020-10-23 12:52:53
React
MrYogurt, 2020-10-23 12:52:53

How to get the current state of useState?

There are 2 components:

const MassViewer:React.FC = (props) => {

    const [checkInput, setCheckInput] = useState<string>('Заполните поле');

    function AddBrand (name: string) {
        let array: string[] = opNames.slice();

            function checkAvailability(array: string[], name: string) {
                return array.some(function(arrVal) {
                    return name === arrVal;
                });
            }
            if (checkAvailability(array, name) === false) {
                setOpNames([...opNames, name]);
                setCheckInput('Добавлено');
    
            } else {
                setCheckInput('Такой оператор уже есть');
            }
    
            function Message(value: string){
                setCheckInput(value);
            }
    }

    ....

    return (
        <div className="allContainers">
            <div className="opNames">
                <ElementList opNames={opNames} />
            </div>
            <div>
                <AddOperator AddBrand={AddBrand} message={checkInput}/>
            </div>
            <div>
                <DelOperator DeleteBrand={DeleteBrand} brand={opNames} />
            </div>
        </div>
);
}

export const AddOperator:React.FC <AddOperatorProps> = (props) => {

    const [message2, setMessage2] = useState<string>(props.message);

    function handleAddOp (e: React.MouseEvent<HTMLElement, MouseEvent>) {
        e.preventDefault();
        const inputResult: string = inputOp.slice();

        if (inputResult.length >= 1) {
            props.AddBrand(inputResult);
            setInputOp('');
            setMessage2(props.message);
        } else {
            setMessage2('Вы не заполнили поле');
            setInputOp('')
        }
    }

    return (
  
  <div>{message2}</div>
        ....
    )
}


When the handleAddOp function is called in the AddOperator component, the contents of the input are sent to the AddBrand function in the MassViewer component. After the conditions are met, the success status is written in the AddOperator component, but the problem is that it is delayed by 1 render. It is late even if you print the console log in the MassViewer component after setting the state. As I understand it, I need to use the useEffect hook, but I didn’t understand how to do it from the documentation, tell me how to implement it.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question