0

I'm very new in React and I need to display data from axios response. It should be in order that is in db, but strangely axios sort my data alphabetically. I check my backend returning data and it's normal. For example original data is:

{
  profession: 'doctor',
  car: 'Honda',
  age: 45,
}

But I got this

{
  age: 45,
  car: 'Honda',
  profession: 'doctor',
}

React Component

function SearchForm({reqForms}) {
  const { register, handleSubmit } = useForm();
  const fetchForms = async (data) => {
    const res = await axios.post("/api/v1/forms/filtered", data)
    console.log(res)
  };
  return (
    <form onSubmit={handleSubmit(fetchForms)} className={styles.searchBar}>
      <input 
        type="text" 
        {...register("profession")} 
      />
      <button>Search</button>
    </form>
  );
}

Maybe you know, where am I wrong?

Evan Serg
  • 27
  • 5

1 Answers1

1

Relying on object property order is not advised (see this answer for more on this). If you wish to have the data displayed in a certain way, you can

  1. use the object properties in ordered columns (ie data.age)
  2. return an array of properties from your backend (ie [{ age: 45 }, { car: 'honda' }, ...

There are other options, but these are the most direct and deterministic.

Abe
  • 4,500
  • 2
  • 11
  • 25