I've been studying react and developing an app, but i got a problem using context. In one component I create the context and provide its value, but when I try to use the current value of context in another component, I have userName:undefined in console.log(). Code:
import React, { useContext, useState } from 'react'
import EnterRoom from '../../Pages/EnterRoom'
import NameChoose from '../../Pages/NameChoose'
import Room from '../../Pages/Room'
export const AllInformation = React.createContext({userName:'default'}) as any
const InformationContextProvider:React.FC = () => {
const [userInformation,setUserInformation] = useState({userName:'newValue'})
return (
<AllInformation.Provider value={{userInformation, setUserInformation}}>
<Room/>
<NameChoose/>
<EnterRoom/>
</AllInformation.Provider>
)
}
export default InformationContextProvider
export function useInformationContext(){
const {userInformation} = useContext(AllInformation)
return { userInformation }
}
And i try to use here:
import React, { useState, FormEvent, useEffect, useContext} from 'react';
import './styles.css'
import { Link, useHistory } from 'react-router-dom';
import { useInformationContext } from '../../components/Context/index'
import io from 'socket.io-client';
function EnterRoom() {
const [roomId, setRoomId] = useState('');
const [name, setName] = useState('');
const history = useHistory();
const socket = io('http://localhost:3333');
const { userInformation } = useInformationContext()
useEffect(() => {
if(sessionStorage.getItem('userName') || sessionStorage.getItem('roomId')) {
history.push('/')
}
console.log({ userInformation })
})
return <h1>hello word</h1>
}
useInformationContext is destructing the context value, which means it's doing value.userInformation, but that key does not exist. Remove the destructuring since the value is not nested:
export function useInformationContext() {
// no destructuring needed here
const userInformation = useContext(AllInformation)
return { userInformation }
}
return directly the useContext hook without destructing.
export function useInformationContext() {
return useContext(AllInformation)
}
Related
import React from 'react';
import axios from 'axios';
import { useEffect, useState } from 'react';
import { useLocation, Link, useNavigate } from 'react-router-dom';
function App() {
const temp = useLocation();
const [username, changeUsername] = useState("guest")
const [password, changePassword] = useState("guest")
const [id, changeId] = useState(-1)
const [data,changeData]=useState(null);
useEffect(() => {
if (temp.state !== null) {
changeUsername(temp.state.username);
changePassword(temp.state.password);
changeId(temp.state.id)
}
},[])
useEffect(() => {
if (id !== -1) {
//fetchdata with axios
changeData(fetchedData)
}
},[id])
return (
<div>
{data!==null && data.map(a => (DataComponent(a))}
</div>
);
}
export default App;
DataComponent also uses react hooks... When I try this with some local data it works, but with fetched data I get "Rendered more hooks than during the previous render".
Currently trying to convert a part of the codebase into Flow. While I was tackling with API calls, I have created a hook to abstract the functionality. However when I tried to import it, the function always returned with a later-added any type.
useApi.js
// #flow
import {useState, useEffect} from 'react';
export default function useApi<T>(
apiCall: (...args: any[]) => Promise<T>,
initialValue:T[]=[]
): T[] {
const [data, setData] = useState(initialValue);
useEffect(() => {
apiCall().then(setData).catch(console.error);
}, [apiCall]);
return data;
}
App.js
import './App.css';
import useApi from './hooks/useApi';
import { getOffers } from './service/Offers';
import { useCallback } from "react";
import Header from "./components/Header";
import Card from "./components/Card";
function App() {
const getOffersMemo = useCallback(() => getOffers(), []);
const offers = useApi(getOffersMemo); // type => OfferModel[] | any
return (//SomeTemplate);
}
export default App;
However when I use export without default keyword it doesn't add any type. What is the reason for this behavior?
i am new in react, how to showing (accountInfo[4]) value in my website?
when i changed to
const setPaid = (accountInfo[4])
TypeError: Cannot read property '4' of undefined
import React, { useState } from 'react';
import useAccountInfo from '../abi/useAccountInfo';
import Value from '../utils/value';
const Hero = () => {
const accountInfo = useAccountInfo();
const setPaid = console.log(accountInfo);
return (
<div>
<Value value={setPaid}/>
</div>
);
export default Hero;
this the result in console
this my useAccountInfo.js file
import { useEffect, useState } from 'react'
import { useWallet } from 'use-wallet'
import { BigNumber } from 'ethers';
import useBlock from './useBlock'
import useTokenInfo from './useTokenInfo';
const useAccountInfo = () => {
const [accountInfo, setAccountInfo] = useState(BigNumber.from(0));
const {account, ethereum} = useWallet();
const block = useBlock();
const tokenInfo = useTokenInfo();
const fetchAccountInfo = async () => {
if (!account) {
setAccountInfo(BigNumber.from(0));
return;
}
const accountInfo = await tokenInfo?.accountInfo();
setAccountInfo(accountInfo);
};
useEffect(() => {
fetchAccountInfo();
}, [block, account, ethereum, tokenInfo]);
return accountInfo;
}
export default useAccountInfo;
I am trying to provide Web3Context.Provider value but it's not updating.
//Web3Context.js
import React from "react";
const Web3Context = React.createContext();
export default Web3Context;
//useWeb3.js
import { useContext } from "react";
import Web3Context from "./Web3Context";
export function useWeb3() {
return useContext(Web3Context);
}
//web3hook.js
export function useDefaultAccount() {
const web3 = useWeb3(); //Undefined, this should be equal to the value provide to Web3Context.Provider
// logic
}
I have provided value to Context in App.js file
//App.js
function App() {
const { web3 } = useWeb3Provider();
const account = useDefaultAccount(); //Undefined because web3 in web3hook.js is undefined
return (
<Web3Context.Provider value={web3}>
</Web3Context.Provider>
);
}
You can use context value in the components which are the child of the contextProvider.
you have to access the context value inside any child of the Web3Context.Provider
function Component() {
const account = useDefaultAccount();
// do something
}
function App() {
const { web3 } = useWeb3Provider();
return (
<Web3Context.Provider value={web3}>
<Component />
</Web3Context.Provider>
);
}
What is the problem with below code? I got warning by typescript when use useState
import * as React, { useState } from 'react'
const useForm = (callback: any | undefined) => {
const [inputs, setInputs] = useState({}) //error: Cannot find name 'useState'.ts(2304)
const handleInputChange = event => {
event.persist()
setInputs(inputs => ({
...inputs,
[event.target.name]: event.target.value,
}))
}
return {
handleInputChange,
inputs,
}
}
export default useForm
https://codesandbox.io/s/react-typescript-starter-lmub8
Your import statement is invalid.
You can either import everything as React like this:
import * as React from 'react';
and the access useState from the React object:
const [inputs, setInputs] = React.useState({})
or import React as the default and only partially import other names:
import React, { useState } from 'react'
And the use useState as before:
const [inputs, setInputs] = useState({});
Try this in formHook.tsx
import React, { useState } from 'react';
and this in app.tsx
import React, { Component } from 'react'
const { inputs, handleInputChange } = useForm;
you can first use React.useState or import it as individual export. second, you should also specify the event object such as change event or form event.
import * as React from 'react'
import {useState} from 'react';
const useForm = (callback: () => void) => {
const [inputs, setInputs] = useState({});
const handleInputChange = (event:React.ChangeEvent<HTMLInputElement>) => {
event.persist()
setInputs(inputs => ({
...inputs,
[event.target.name]: event.target.value,
}))
}
return {
handleInputChange,
inputs,
}
}
export default useForm