0

Learning React thanks to your advices, I ended with this simple example, where everything runs nice & smooth. Question is: how can I implement a sort() method to order those data? ( I mean to show table Users ordering by LastName)....

PhoneBookForm:

import {useState} from 'react';
import InformationTable from './InformationTable';
export default function PhoneBookForm() {

    
    const[user,setUser] = useState([]);

    const [input,setInput]=useState({
        firstName:'',
        lastName:'',
        phone:'',
    });  
    
    function handleChange(e){      
      setInput({
        ...input,
        [e.target.name]:e.target.value
      })
  
    }
  
    function handleSubmit(e){
      console.log(user)
      e.preventDefault();
      setUser(
        
      [...user,{...input}])
      setInput({
        ...input,
        firstName:'',
        lastName:'',
        phone:''
      
    })}
  
  
    return (
      <>
      <form onSubmit={e => { e.preventDefault() }} style={style.form.container}>
        <label>First name:</label>
        <br />
        <input 
          style={style.form.inputs}
          className='userFirstname'
          name='firstName' 
          type='text'
          placeholder='Enter your name here...'
          value={input.firstName}
          onChange={handleChange}
        />
        <br/>
        <label>Last name:</label>
        <br />
        <input 
          style={style.form.inputs}
          className='userLastname'
          name='lastName' 
          type='text' 
          placeholder='Enter your Last Name here...'
          value={input.lastName}
          onChange={handleChange}
        />
        <br />
        <label>Phone:</label>
        <br />
        <input
          style={style.form.inputs}
          className='userPhone' 
          name='phone' 
          type='text'
          placeholder='Enter your phone number...'
          value={input.phone}
          onChange={handleChange}
        />
        <br/>
        <input 
          style={style.form.submitBtn} 
          className='submitButton'
          type='submit' 
          value='Add User' 
          onClick={handleSubmit}
        />
      </form>
      
      <InformationTable user={user}/>
      </>
    )
  }

InformationTable :

export default function InformationTable({user}) {

    // console.log(user);
    return (      
            <div>
             {user?.map((u)=>{
              return(
                <div key={u.phone}>
                <table style={style.table} className='informationTable'>
                <thead> 
                <tr>
                <th style={style.tableCell}>{u.firstName}</th>
                <th style={style.tableCell}>{u.lastName}</th>
                <th style={style.tableCell}>{u.phone}</th>
                </tr>
              </thead> 
              </table>
              </div>
              )
            })}
          </div>
    );
  }

Currently, User data is showing, but with no order at all

Martin Gonzalez
  • 77
  • 1
  • 1
  • 12
  • 1
    so .sort() it. Do it when you set the data – epascarello Nov 23 '21 at 16:05
  • I would use `sor()` like `[...user,{...input}].sort(someSortFunction)` right before `setUser`. I wouldn't do it in render while using `.map`. – Jax-p Nov 23 '21 at 16:06
  • [`.map` should not have side effects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#when_not_to_use_map). You map the array, and then you [sort it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) (or your sort then map it) – Ruan Mendes Nov 23 '21 at 16:09
  • @Jax-p - thanks Jax. – Randy Casburn Nov 23 '21 at 16:13

1 Answers1

1

Using state inside setState is React antipattern. SetState function has an callback with previous state, e.g.:

setState(previouState => previousState + 1)

Knowing this, you have two possibilities to sort your users. Directly in setUser function or directly when rendering. Your handleSubmit function then could look like this

function handleSubmit(e){
      console.log(user)
      e.preventDefault();
      setUser(prevUserState => {
           newUsersArray = [...prevUserState, input]
           newUsersArray.sort((a,b) => 
                { if (a.lastName > b.lastName) { 
                   return 1 
                } else { 
                   return -1
                }
           })
        
      )
      setInput({
        firstName:'',
        lastName:'',
        phone:''
      
    })}

If you want to sort the users till on rendering, then simply:

 <div>
             {user.sort((a,b) => {
                  if (a.lastName > b.lastName) return 1
                  else return -1
              }).map((u)=>{
              return(...
Fide
  • 1,127
  • 8
  • 7