(React)At rendering, initial value of zustand comesout firstly Please, give me your opinions

22 Views Asked by At

I made a zustandStore and i put the initial value at there. And at other component i set zustand to the other value. And go to other page and come again, if i console the zustand value, then the first value come firstly. So when I props or use the zustand, the outcome is different with my thought.

the main code

const {
    zustandMonitorUsage,
    setZustandMonitorUsage,
  } = useFirstSurveyStore();

const handleClick = (index: number) => {
    // eslint-disable-next-line no-console
    const answer: 1 | 2 | 4 | 8 | 16 = content[index][2];
    setZustandMonitorUsage(answer);
    isFocus = answer;
  };

  console.log('focus: ', isFocus, 'zus: ', zustandMonitorUsage);

  return (
    <div className={styles.container}>
      <SurveyBox
        content={content}
        boxClick={handleClick}
        design={'fiveStyles'}
        isFocus={isFocus}
      />
    </div>
  );
import {useState} from 'react';

const SurveyBox = ({
  content,
  boxClick,
  design,
  isFocus,
}: {
  content: (JSX.Element | string | number | boolean)[][];
  boxClick: (index: number) => void;
  design: string;
  isFocus: string | number | boolean;
}) => {
  const [value, setValue] = useState<JSX.Element | string | number | boolean>(
    isFocus,
  );
 const handleBoxClick = (index: number) => {
    boxClick(index);
    setValue(content[index][2]);
  };

  return (
    <div className={dContainer}>
      {content.map((item, index) => (
        <div key={index}>
          <button
            className={item[2] === value ? dFocusBox : dBox}
            onClick={() => handleBoxClick(index)}
          >
          </button>
        </div>
      ))}
    </div>
  );

interface IFirstSurveyStore {
  zustandMonitorUsage: -1 | 1 | 2 | 4 | 8 | 16;
  setZustandMonitorUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) => void;
}

const useFirstSurveyStore = create<IFirstSurveyStore>()(
  persist(
    set => ({
      zustandMonitorUsage: -1,
      setZustandMonitorUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) =>
        set({zustandMonitorUsage: newUsage}),
    }),
    {name: 'FirstSurvey'},
  ),
);

this is my all code

'use client';

import {useState} from 'react';
import Question from '@/components/Survey/Question';
import SurveyBox from '@/components/Survey/SurveyBox';
import useFirstSurveyStore from '@/stores/firstSurvey';
import styles from '@/components/Survey/index.module.scss';
/**
 * 내용, 클릭 체크 함수, 선택지 중복 개수 넣기
 */
const Form = () => {
  const [isClicked, setIsClicked] = useState<boolean>(false);
  const {
    zustandMonitorUsage,
    setZustandMonitorUsage,
    setZustandMouseUsage,
    setZustandKeyboardUsage,
  } = useFirstSurveyStore();
  const questionContent = '어떤 용도로 사용하실 건가요?';
  const presentPage: string = '1';
  const content: [string, string, 1 | 2 | 4 | 8 | 16][] = [
    ['사무', '', 1],
    ['게임', '', 2],
    ['개발', '', 4],
    ['영상', '', 8],
    ['취미', '', 16],
  ];

  let isFocus: string | number | boolean = zustandMonitorUsage;

  const handleClick = (index: number) => {
    // eslint-disable-next-line no-console
    const answer: 1 | 2 | 4 | 8 | 16 = content[index][2];
    setZustandKeyboardUsage(answer);
    setZustandMonitorUsage(answer);
    setZustandMouseUsage(answer);
    setIsClicked(true);
    isFocus = answer;
  };
  console.log('focus: ', isFocus, 'zus: ', zustandMonitorUsage);
  return (
    <div className={styles.container}>
      <Question questionContent={questionContent} />
      <SurveyBox
        content={content}
        boxClick={handleClick}
        design={'fiveStyles'}
        isFocus={isFocus}
      />
    </div>
  );
};
export default Form;

/* eslint-disable @next/next/no-img-element */
import {useState} from 'react';
import twoStyles from '@/components/Survey/SurveyBoxTwo.module.scss';
import threeStyles from '@/components/Survey/SurveyBoxThree.module.scss';
import fourStyles from '@/components/Survey/SurveyBoxFour.module.scss';
import fiveStyles from '@/components/Survey/SurveyBoxFive.module.scss';

const SurveyBox = ({
  content,
  boxClick,
  design,
  isFocus,
}: {
  content: (JSX.Element | string | number | boolean)[][];
  boxClick: (index: number) => void;
  design: string;
  isFocus: string | number | boolean;
}) => {
  const [value, setValue] = useState<JSX.Element | string | number | boolean>(
    isFocus,
  );

  let dContainer: string | undefined;
  let dBox: string | undefined;
  let dFocusBox: string | undefined;
  let dPositionContainer: string | undefined;
  let dContent: string | undefined;

  if (design === 'twoStyles') {
    dContainer = twoStyles.container;
    dBox = twoStyles.box;
    dFocusBox = twoStyles.focusBox;
    dPositionContainer = twoStyles.positionContainer;
    dContent = twoStyles.content;
  } else if (design === 'threeStyles') {
    dContainer = threeStyles.container;
    dBox = threeStyles.box;
    dFocusBox = threeStyles.focusBox;
    dPositionContainer = threeStyles.positionContainer;
    dContent = threeStyles.content;
  } else if (design === 'fourStyles') {
    dContainer = fourStyles.container;
    dBox = fourStyles.box;
    dFocusBox = fourStyles.focusBox;
    dPositionContainer = fourStyles.positionContainer;
    dContent = fourStyles.content;
  } else {
    dContainer = fiveStyles.container;
    dBox = fiveStyles.box;
    dFocusBox = fiveStyles.focusBox;
    dPositionContainer = fiveStyles.positionContainer;
    dContent = fiveStyles.content;
  }

  const handleBoxClick = (index: number) => {
    boxClick(index);
    setValue(content[index][2]);
  };

  return (
    <div className={dContainer}>
      {content.map((item, index) => (
        <div key={index}>
          <button
            className={item[2] === value ? dFocusBox : dBox}
            onClick={() => handleBoxClick(index)}
          >
            <div className={dPositionContainer}>
              <div className={dContent}>{item[0]}</div>
              {item[1] !== '' &&
                typeof item[1] === 'string' &&
                typeof item[0] === 'string' && (
                  <div>
                    <img src={item[1]} alt={item[0]}></img>
                  </div>
                )}
            </div>
          </button>
        </div>
      ))}
    </div>
  );
};

export default SurveyBox;

<Zustand - store>

import {create} from 'zustand';

import {persist} from 'zustand/middleware';
// 용도, 가격, 색
interface IFirstSurveyStore {
  zustandMonitorUsage: -1 | 1 | 2 | 4 | 8 | 16;
  setZustandMonitorUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) => void;
  zustandKeyboardUsage: -1 | 1 | 2 | 4 | 8 | 16;
  setZustandKeyboardUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) => void;
  zustandMouseUsage: -1 | 1 | 2 | 4 | 8 | 16;
  setZustandMouseUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) => void;
  zustandTotalPrice: number;
  setZustandTotalPrice: (newPrice: number) => void;
  zustandColor: 'INIT' | 'BLACK' | 'WHITE' | 'COLOR' | 'NONE';
  setZustandColor: (
    newColor: 'INIT' | 'BLACK' | 'WHITE' | 'COLOR' | 'NONE',
  ) => void;
  resetFirstSurvey: () => void;
}

const useFirstSurveyStore = create<IFirstSurveyStore>()(
  persist(
    set => ({
      zustandMonitorUsage: -1,
      setZustandMonitorUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) =>
        set({zustandMonitorUsage: newUsage}),
      zustandKeyboardUsage: -1,
      setZustandKeyboardUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) =>
        set({zustandKeyboardUsage: newUsage}),
      zustandMouseUsage: -1,
      setZustandMouseUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) =>
        set({zustandMouseUsage: newUsage}),
      zustandTotalPrice: 0,
      setZustandTotalPrice: (newPrice: number) =>
        set({zustandTotalPrice: newPrice}),
      zustandColor: 'INIT',
      setZustandColor: (
        newColor: 'INIT' | 'BLACK' | 'WHITE' | 'COLOR' | 'NONE',
      ) => set({zustandColor: newColor}),
      resetFirstSurvey: () => {
        set({
          zustandMonitorUsage: -1,
          zustandKeyboardUsage: -1,
          zustandMouseUsage: -1,
          zustandTotalPrice: 0,
          zustandColor: 'INIT',
        });
      },
    }),
    {name: 'FirstSurvey'},
  ),
);

export default useFirstSurveyStore;
export type {IFirstSurveyStore};

I console the zustandMonitorUsage value(i set the value to 4) but it came -1 and after it came 4 but the first value is -1, so the props go -1

I want to know why the initial value of zustand comes first

0

There are 0 best solutions below