'Why I can't update state with Context API

I Make Kakaotalk with ReactJS

I make Search User Page now, and I use Context API because use Global State

addFriend/Index.tsx

import Header from "components/friends/Header";
import InputUserId from "./InputUserId";
import Profile from "./Profile";
import { AddFriendProvider } from "./AddFriendContext";

const AddFriend = () => {
  <>
    <AddFriendProvider>
      <Header />
      <InputUserId />
      <Profile />
    </AddFriendProvider>
  </>;
};

export default AddFriend;

addFriend/AddFriendContext.tsx

import React, { createContext, useState } from "react";

const AddFriendContext = createContext<any>({
  state: {
    userId: "",
    searchResult: "",
  },
  actions: {
    setUserId: () => {},
    setSearchResult: () => {},
  },
});

const AddFriendProvider = ({ children }: any) => {
  const [userId, setUserId] = useState("");
  const [searchResult, setSearchResult] = useState("");

  const value = {
    state: { userId, searchResult },
    actions: { setUserId, setSearchResult },
  };

  console.log(value);

  return (
    <AddFriendContext.Provider value={value}>
      {console.log(setUserId, setSearchResult)}
      {children}
    </AddFriendContext.Provider>
  );
};

export { AddFriendProvider };

export default AddFriendContext;

addFriend/InputUserId.tsx

import styled from "styled-components";
import Input from "components/common/Input";
import { ChangeEvent, useContext } from "react";
import AddFriendContext from "./AddFriendContext";

const StyledInputWrapper = styled.div`
  width: 370px;
  height: 80px;
  display: flex;
  align-items: center;
`;

const InputUserId = () => {
  const { state, actions } = useContext(AddFriendContext);
  console.log(state, actions);

  const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    actions.setUserId(value);
  };

  const inputStyle = {
    width: "100%",
    height: "40px",
    paddingLeft: "10px",
    fontWeight: "bold",
  };

  const subInputStyle = {
    borderBottom: "2px solid lightgray",
    focus: "2px solid black",
  };

  return (
    <StyledInputWrapper>
      <Input
        type="text"
        placeholder="카카오톡 아이디를 입력해주세요."
        required
        inputStyle={inputStyle}
        subInputStyle={subInputStyle}
        value={state.userId}
        onChange={onChange}
      />
    </StyledInputWrapper>
  );
};

export default InputUserId;

If i change input element in InputUserId.tsx call actions.setUserId(value) but It not worked.

I think login is >

  1. When Change Input, call actions.setUserId and update state.userId
  2. Change Input value when state.userId Update
  3. But it now Worked..

Help me and if some trouble in my code feedback me plz. thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source