Home > OS >  Sorting request response by date and then setting state with it
Sorting request response by date and then setting state with it

Time:01-03

I currently have this function:

 const fetchJobs = async (userId: string) => {
        setJobs([])

        await axios.post("/api/fetch/fetchMany?type=jobs", {
            user_id: userId
        })
        .then((response) => {
            if (response == null || response.data.length === 0) {
                setJobs([])
            } else {
                const sortedJobs = response.data.sort = (a: Date, b: Date): Job[] => {
                    return new Date(a.startDate) - new Date(b.startDate)
                }
                setJobs(sortedJobs)
            } 
        })
    }

What it does is fetches a list of 'job' objects, and then attempts to sort them from newest to oldest, before placing them inside of jobs state.

However, there are two issues:

  1. I'm getting a 'startDate' does not exist on type 'Date' in the sort function
  2. The function is not assignable to parameter of type 'SetStateAction<Job[]>'

For some context, here's my Job type, which is an array of objects:

export type Job = {
    _id: string,
    user_id: string, 
    jobTitle: string, 
    employer: string,
    responsibilities: string[], 
    startDate: string | Date,
    endDate: string
}

And then here's my state type:

const [jobs, setJobs] = useState<Job[]>([])

I think I need to change what my state can be set as, but I don't understand why I can't set the state using the function, as it returns an array of job types.

Any help would be really appreciated

CodePudding user response:

type the axios request await axios.post<Job[]>(...) so response.data is automatically typed accordingly.

Array#sort() is a method, not a property. It expects a callback function that recieves two values from the array (which in your case are of type Job, not Date) and returns a signed number based on their order. Not a boolean.
response.data.sort((a, b) => new Date(a.startDate) - new Date(b.startDate))

And don't mix async/await with .then()

so overall

const fetchJobs = async (userId: string) => {
  setJobs([])

  const response = await axios.post<Job[]>("/api/fetch/fetchMany?type=jobs", {
    user_id: userId
  });

  if (!response || response.data.length === 0) {
    // setJobs([]) // you've already done that
    return;
  }

  const sortedJobs = response.data.sort((a, b) => new Date(a.startDate) - new Date(b.startDate));

  setJobs(sortedJobs);
}

CodePudding user response:

Use either async/await or Promise while handling network tasks

const fetchJobs = async (userId: string) => {
  setJobs([])  //            
  • Related