简体   繁体   中英

Can I use server-side props from getServerSideProps to initialize dynamic state in NextJS?

I'm currently creating a simple application using NextJS and I'm wondering what the best way is to handle SSR using data from an API that will also be dynamic on the page. My current approach is outlined as follows, and I'm curious as to whether this is how it should be done in NextJS.

I retrieve a set of todos from the free JSON Placeholder API using getServerSideProps inside of my Home page component as follows (please note that I'm using TypeScript):

export const getServerSideProps: GetServerSideProps = async () => {
  const todoAPIResponse = await fetch('https://jsonplaceholder.typicode.com/todos?_limit=10');
  const todos = await todoAPIResponse.json();

  return {
    props: {
      todos,
    },
  };
};

The Home component is defined as:

const Home: NextPage = ({ todos }: HomeProps) => {

  const [todoState, setTodoState] = useState(todos);
  const [newTodo, setNewTodo] = useState('');

  const onSubmit = (event: any) => {
    event.preventDefault();
    setTodoState((prev: any) => [...prev, { title: newTodo }]);
    setNewTodo('');
  };

  return (
    <div className={styles.container}>
      {todoState.map((todo: any) => <p key={todo.id}>{todo.title}</p>)}
      <form onSubmit={onSubmit}>
        <input value={newTodo} onChange={(event) => setNewTodo(event.target.value)} />
      </form>
    </div>
  );
};

As you can see inside of the Home component, I am initializing todoState using the props (the data retrieved from the API), and then the data becomes dynamic with the ability to create new todos with the form. In the typical "React way", I understand that the todos would be initialized as an empty array, then inside of a useEffect , the API could be called and then the state could be set from there, however, I'm trying to understand what the proper way of doing this in NextJS is as I am new to the framework and the concept of SSR.

I believe you are doing it right.

The approach between ssr and react is different. In the ssr version, you need a server first, so that each call to this page would make this fetch before a HTML page is assembled and sent back to the UI . And afterwards, the NextJS will hydrate this page to make it like a regular React page by attaching all the other dynamic attributes.

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