• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

176
Views
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.

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error