0

I'm learning react native. I didn't figure out this problem. I have been using functional component in my project. Here is i don't understand to convert class component state :

 constructor(props) {
        super(props)
        this.state = {
          center: { lat: 5.6219868, lng: -0.23223 },
          locations: {},
          users_online: [],
          current_user: ''
        }
      }

   /* this.setState((prevState, props) => { 
              let newState = { ...prevState };
              newState.center = location;
              newState.locations[`${prevState.current_user}`] = location;
              return newState;
            }); */ ==> I wan't to convert to functional component this state. 

Thank you for answering.!

2 Answers2

2

It's pretty simple, although I would suggest you to checkout hooks concepts in react.

const [data, setData] = useState({
          center: { lat: 5.6219868, lng: -0.23223 },
          locations: {},
          users_online: [],
          current_user: ''
        });



//one way
         setData((prevState) => ({ 
             ...prevState,
             center = location;
             locations[`${prevState.current_user}`] = location;
            }));

//another way
    
    const handleTextChange = (text,field) => {
        setStates(prev => ({
            ...prev,
            [field]: text,
        }))
    };;

Also, you can main 4 different states as well.

const [center, setCenter] = useState({ lat: 5.6219868, lng: -0.23223 });
const [locations, setLocations] = useState({});
const [usersOnline, setUsersOnline] = useState([]);
const [currentUser, setCurrentUser] = useState('');
Akshay Shenoy
  • 1,194
  • 8
  • 10
  • Thank you for answering. After implement code let newState = { ...prevState }; newState.locations is undefinied. Did let newState = { ...prevState }; mean is copy that object? didn't it. Why After implement this code let newState = { ...prevState } undefined. Do you have any idea of that – Золбоо О' Jan 14 '22 at 10:04
  • Edited my answer, that might help – Akshay Shenoy Jan 14 '22 at 10:24
1

This is kind of a broad question and I think you should follow any getting started with hooks tutorial to understand what's going on. Anyways, in your case, you will first need to change it into a function instead of a class, then specify the four states values you have using an useState for each. For the batched updates, wrap the state settings functions inside an unstable_batchedUpdates method to trigger a single rerender for multiple state updates. Keep in mind, that the last method is unstable and might change in the future, but that gets things done for now.

Hisham Mubarak
  • 1,559
  • 3
  • 22
  • 28