Home > Back-end >  get the state of a function component for my url in getStaticProps
get the state of a function component for my url in getStaticProps

Time:12-16

i want to fetch data from an input so i create a controlled component like this

import React, { useState } from "react";
import axios from 'axios'


type Props = {data:any};


function Locality({data}: Props) {

const [city, setCity] = useState("13000");

return(

 <input
  list="city"
  type="text"
  placeholder={`Code postale, France`}
  onChange={(e) => {
   setCity(e.target.value) ;
   }}
  />
 )
}

i want to fetch an url according to the city set in the state but i don't know how to give this state to my fetch below:

export async function getStaticProps(){
const getDataUrl:string = `https://geo.api.gouv.fr/communes?codePostal=${city}&format=geojson`

const result = await axios.get(getDataUrl)
const data = result.data

  return {
    props:{
      data : data.data[0].attributes
    }
  }
}

any idea ?

CodePudding user response:

nextjs Edit thirsty-joana-7pgrym

You might also want to investigate nextjs getServerSideProps

CodePudding user response:

As pointed out by @ksav, you would need to use some local state, but also, an effect to fetch the data.

Here is an example how to do that: (untested, for the idea)

import React, { useState } from "react";
import axios from 'axios'


type Props = {data:any};


function Locality({data}: Props) {

const [city, setCity] = useState("13000");
// That will contain the result of the fetch
const [isFetching, setIsFetching] = useState(false)
const [result, setResult] = useState(null);
const [error, setError] = useState(null);

useEffect(function fetchResults() {

      const getDataUrl:string = `https://geo.api.gouv.fr/communes?codePostal=${city}&format=geojson`
      setIsFetching(true)
      const result = axios.get(getDataUrl).then(res => {
        const data = result.data

        setResult(data.data[0].attributes)
      }).catch(setError).finally(() => {
        setIsFetching(false)
      })
}

return(

 <input
  list="city"
  type="text"
  placeholder={`Code postale, France`}
  onChange={(e) => {
   setCity(e.target.value) ;
   }}
  />{isFetching && 'Loading...'}
{!error && !isFetching && 
<div>Result for {city}: {result}</div>}
 )
}

If you use the above effect that I or @ksav suggested, I suggest you look for XHR cancelation and effect debouncing, to avoid bugs that will occur as the user types in the box and many requests are sent at the same time. For example if I type '75000', it will send 5 requests, and if the 3rd request is the slowest, result can finally contain the result for 750, not 75000.

  • Related