Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Dynamic API routing with getServerSideProps in Nextjs

I want to fetch Dynamic API routing after enter submit with input state. but I don't know how to pass state from react to getServerSideProps.

this is my code

export default function Home(props) {
    const { data } = props;
    const [input, setInput] = useState("");
    const handlerChange = (event) => {
        setInput(event.target.value);
    };
    const handlerSubmit = () => {
        console.log(event.target.value);
        setInput("");
    };

    return (
        <input
            type="text"
            className="form-control"
            placeholder="Group Name"
            value={input}
            onChange={handlerChange}
            onKeyDown={(event) =>
                event.key === "Enter" && handlerSubmit(event)
            }
        />
    )

export async function getServerSideProps() {
    const res = await fetch(`http://localhost:3000/api/searchGroup/${input}`)
    const data = await res.json()
  
    return { props: { data } }
}
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could use a dynamic route instead to navigate to something like a /your-current-page/${input} and you would then have access to the input value as a param in getServerSideProps as such:

export async function getServerSideProps({ params }) {
    const { input } = params;
     
    ...
}

More info on this here

about 4 years ago · Santiago Trujillo Relatório

0

You should make the request with the updated input value from the client-side instead inside the handlerSubmit callback and save the data to be rendered in a state variable (e.g. dataToRender).

const getData = async (input) => {
    const res = await fetch(`http://localhost:3000/api/searchGroup/${input}`)
    return res.json()
}

export default function Home(props) {
    const { data } = props;
    const [dataToRender, setDataToRender] = useState(data);
    const [input, setInput] = useState("");

    const handlerChange = (event) => {
        setInput(event.target.value);
    };

    const handlerSubmit = async (event) => {
        setInput("");
        const newData = await getData(event.target.value);
        setDataToRender(newData);
    };

    return (
        <input
            type="text"
            className="form-control"
            placeholder="Group Name"
            value={input}
            onChange={handlerChange}
            onKeyDown={(event) =>
                event.key === "Enter" && handlerSubmit(event)
            }
        />
    )
}

As an alternative to the above, if you absolutely need to have the request in getServerSideProps, then you can pass the input value as a query parameter and read it from context.query.input in getServerSideProps.

// On the client-side
import { useRouter } from "next/router";

export default function Home(props) {
    const router = useRouter()    

    const handlerSubmit = () => {
        console.log(event.target.value);
        setInput("");
        router.push(`${router.pathname}?input=${event.target.value}`);
    }
    
    // Remaining code...
}
// On the server-side
export async function getServerSideProps(context) {
    const res = await fetch(`http://localhost:3000/api/searchGroup/${context.query.input ?? 'default-value'}`)
    const data = await res.json()
  
    return { props: { data } }
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda