skip to Main Content

I am building a frontend application with react

i want to store the value of phone on useState but i am not getting the expected result

The last character typed does not show

I have used callback to display the same result

  import React, { useState } from 'react'
    export const terr = () => {
        const [selectedData, setSelectedData] = useState({})
    
        const handleChange = (value) => {
            console.log(`selected ${value}`);
            setSelectedData(selectedData => ({
                ...selectedData,
                [e.target.name]: e.target.value
            }));
            console.log(`selected data `, selectedData);
        };
        return (
            <div>
                <input name="phone" value={selectedData} onChange={handleChange} />
            </div>
        )
    }

2

Answers


  1. I think this is what you wanted to achieve

    export const Server = () => {
      const [selectedData, setSelectedData] = useState({});
    
      const handleChange = (e) => {
        setSelectedData({ ...selectedData, [e.target.name]: e.target.value });
      };
    
      return (
        <div>
          <input name="phone" onChange={(e) => handleChange(e)} />
        </div>
      );
    };
    

    Note that the console.log inside the handleChange function always shows an "old" selectedData value because setSelectedData is async, try logging it with useEffect or directly inside the JSX to confirm

    Login or Signup to reply.
  2. What seems to be wrong with your code is two things:

    1. The value property on the input is not needed
    2. The handleChange function should take a parameter of event (see HTMLElement: change event)
    import { FC, useEffect, useState } from 'react';
    
    // https://stackoverflow.com/a/77504979/128346
    export const App: FC = () => {
      const [selectedData, setSelectedData] = useState<{
        phone?: string;
        words?: string;
      }>({});
    
      const handleChange = (event) => {
        const { name, value } = event.target;
        setSelectedData({
          ...selectedData,
          [name]: value,
        });
      };
    
      useEffect(() => {
        console.log(`selected data `, selectedData);
      }, [selectedData]);
    
      return (
        <div>
          <input
            name="phone"
            value={selectedData.phone ?? ''}
            onChange={handleChange}
          />
          <input
            name="words"
            value={selectedData.words ?? ''}
            onChange={handleChange}
          />
        </div>
      );
    };
    

    sandboxed demo of the above in action
    https://stackblitz.com/edit/stackblitz-starters-yhksn3?file=src%2FApp.tsx

    video demo of the above in action
    https://www.loom.com/share/4751379be5c04f10adcb61e241551b90


    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search