简体   繁体   中英

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 } }
}

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

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 (eg 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 } }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM