teafuljs / teaful

🍵 Tiny, easy and powerful React state management
https://npm.im/teaful
MIT License
712 stars 25 forks source link

How to dynamic setting initial value with Next.js #82

Closed wh5938316 closed 2 years ago

wh5938316 commented 2 years ago

What version of this package are you using? 0.10.0

What problem do you want to solve? Dynamic setting initial value with Next.js

my Next.js page file like this

import { InferGetServerSidePropsType } from "next";
import * as React from "react";
import createStore from "teaful";

export const { useStore, setStore } = createStore({ name: "nothing" });

export default function MyPage({
  name,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  const [storeName] = useStore.name();

  React.useEffect(() => {
    setStore.name(name);
  }, []);

  console.log(storeName);

  return <div>{storeName}</div>;
}

export const getServerSideProps = async () => {
  return {
    props: { name: "hello teaful" },
  };
};

console.log like this

nothing
hello teaful

I want to set initial value dynamically. Keep console.log always print hello teaful in this case. Can Teaful achieve this?

aralroca commented 2 years ago

Yes, you can use const [storeName] = useStore.name('nothing'). The param is for the initial value in case that doesn't have.

wh5938316 commented 2 years ago

Thank you very much. Teaful is easy to use, API design is smart. Here is code for Teaful.js and Next.js SSG

import { InferGetServerSidePropsType } from "next";
import * as React from "react";
import createStore from "teaful";

type Initial = {
  name: string;
};

export const { useStore, setStore } = createStore<Initial>();

export default function MyPage({
  name,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  const [storeName] = useStore.name(name);

  console.log(storeName);

  return <div>{storeName}</div>;
}

export const getServerSideProps = async () => {
  return {
    props: { name: "hello teaful" },
  };
};
aralroca commented 2 years ago

Thank you! That's one of Teaful's goals, to make it easy. Any suggestions or issues feel free to report them! Or if you want to add an example with Next.js it would be very welcome! 😊