Nakul Nagariya
Nakul Nagariya

Reputation: 107

How to recall getServerSideProps from same component with updated api url?

I want to pass the params in this function to get the updated/filtered data on the same page when some filters applied?

This is working fine for the initial rendering but i'm unable to get updated data from my same component as this getServerSideProps function is outside of my component.

Mycomponent

let API_URL = `https://api.spaceXdata.com/v3/launches?limit=100`
const spacex = ({ missions }) => {
  const [allMissions, setallMissions] = useState(missions)

  const filterResults = (filter, value) => {
    getServerSideProps(`${API_URL}&${filter}=${value}`) // but this is not accessible from here, getServerSideProps is undefined here as this is outside the function
  }

render() {
 return (
  {missions.map((mission) => <li>mission.name</li>)}
 )
}
export const getServerSideProps = async (API_URL) => {
  const res = await fetch(API_URL)
  const missions = await res.json()
  if (!missions) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }
  return {
    props: {
      missions,
    },
  }
}

Upvotes: 5

Views: 1218

Answers (1)

juliomalves
juliomalves

Reputation: 50358

You can't call getServerSideProps from your component on the client, getServerSideProps only runs on the server.

Instead, you should make a request directly from the client whenever you need to filter the data.

const API_URL = `https://api.spaceXdata.com/v3/launches?limit=100`

const SpaceX = ({ missions }) => {
    const [allMissions, setAllMissions] = useState(missions)

    const filterResults = async (filter, value) => {
        const res = await fetch(`${API_URL}&${filter}=${value}`)
        const missions = await res.json()
        setAllMissions(missions)
    }

    return (
        {allMissions.map((mission) => <li>mission.name</li>)}
    )
}

Upvotes: 2

Related Questions