Why I can not initialize value in useState? - javascript

tiles is an array of objects
var intialTiles = tiles;
const [newTiles, setNewTiles] = useState(intialTiles);
when I console log newTiles i see undefined , what could be the reson ?

You can send the props to the component this way, <App tiles={[123, 4546]} />
And in the App component,
import "./styles.css";
import { useState, useEffect } from "react";
export default function App(props) {
var intialTiles = props.tiles;
const [newTiles, setNewTiles] = useState(intialTiles);
useEffect(() => {
console.log(newTiles);
}, [newTiles]);
function update() {
setNewTiles([...newTiles, parseInt(Math.random() * 2345, 10)]);
}
return (
<div className="App">
<button onClick={update}>update</button>
<h2>Please check the console output</h2>
</div>
);
}
Hope it helps! live demo here: https://codesandbox.io/s/cocky-bash-23o700?file=/src/App.js:0-506

Related

How to put React hooks into for loop?

I want append a div container with divs. The divs quantity is the data json's length. I have tried to put the hooks inside the for loop, but it throwed error.
The project's github link:
https://github.com/folza1/react-modulzaro
import "./App.css";
import React, { useEffect, useRef } from "react";
function App() {
var data = require("./data.json");
//for(let i=0;i<data.length;i++{WHAT COPY HERE TO APPEND THE 30 divProduct?})
const container = useRef(null);
const divProduct = document.createElement("div");
divProduct.classList.add("divStyle");
useEffect(() => {
container.current.appendChild(divProduct);
}, []);
return (
<div>
<div id={"container"} ref={container} />
</div>
);
}
export default App;
The example code posted seems somewhat confused with regards to how React works.
Assuming data is an array of objects, all you would need for this is something like the following:
import "./App.css";
import * as React from "react";
const data = [
{id: "1", name: "obj1"},
{id: "2", name: "obj2"},
{id: "3", name: "obj3"}
];
function App() {
return (
<div id="container">
{data.map(obj => <p key={obj.id}>{obj.name}</p>)}
</div>
);
}
export default App;

create a array of random number then usestate hooks updates each and every time

Whenever i try to create a array of random number then usestate hooks updates each and every time. I also tried using bool values but still it re-render . Please help me how to solve this problem.
import './App.css';
import { useEffect, useState, useCallback } from 'react';
function App() {
const [arr, setArr] = useState([]);
var isLoaded = false;
function add() {
let array = [];
for(var i=0;i<=20;i++){
array.push(Math.floor(Math.random*(10-6))+6);
}
if(!isLoaded){
setArr(array);
console.log('yes');
isLoaded = true;
}
}
add();
return (
<div>
</div>
);
}
export default App;
setArr(array) causes the component to be rendered again. When it is rendered, isLoaded is defined as false again and everything starts over because you call the function add() inside the component.
You can try this.
export default function App() {
const [arr, setArr] = useState(() =>
Array.from({ length: 20 }, (_) => Math.floor(Math.random() * (10 - 6)) + 6)
);
return (
<div></div>
);
}

Context values not updating in react js

I have created a counter app in React js using context api for global state management .
But the problem is when i am clicking increase and decrease button it is not updating global values .
I am new to react , please provide guidance what is going wrong here .
ContextFile :
import {createContext,useState} from 'react';
export const DataContext = createContext({
data:0,
increase : () => {},
decrease : () => {}
});
function DataContextProvider(props){
const [data,setData] = useState();
const increase = () => {
setData(data + 1);
}
const decrease = () => {
setData(data - 1);
}
return(
<DataContext.Provider value={{data,increase,decrease}}>
{props.children}
</DataContext.Provider>
);
};
export default DataContextProvider;
App.js :
import React,{useContext} from 'react';
import {DataContext} from './Context/dataContext';
import DataContextProvider from './Context/dataContext';
import IncreaseBtn from './Component/Increase';
import DecreaseBtn from './Component/Decrease';
const App = () => {
const {data} = useContext(DataContext);
return(
<>
<DataContextProvider>
{data}
<br/>
<br/>
<IncreaseBtn />
<br/>
<br/>
<DecreaseBtn />
</DataContextProvider>
</>
)
}
export default App;
Increase Button Component :
import React,{useContext} from 'react';
import {DataContext} from '../Context/dataContext';
const IncreaseBtn = () => {
const {increase} = useContext(DataContext);
return(
<>
<button onClick={increase}> Increase </button>
</>
)
}
export default IncreaseBtn;
Decrease Button Component :
import React,{useContext} from 'react';
import {DataContext} from '../Context/dataContext';
const DecreaseBtn = () => {
const {decrease} = useContext(DataContext);
return(
<>
<button onClick={decrease}> Decrease </button>
</>
)
}
export default DecreaseBtn;
Folder Structure :
If you want to use context you should wrap your provider around those components, but here App component isn't wrapped but to its children 😉
Give an initial state of some "number" as it would be undefined and it gives NaN if you do the arithmetic operations with it.
Updated the sandbox for your ref
You are updating the state in the wrong way
Try:
setCount(count => count + 1);

When useState update then map loop is not working in array inside of object in useState. React js

When useState update then map loop is not working in array inside of object in useState. React js
import { useState } from "react";
import React from "react";
function Check() {
const [Children, setChildren] = useState({data:[], otherdata:{}});
function handleChange(){
Children["data"] = [...Children["data"], Children["data"].length]
setChildren(Children)
alert(Children["data"])
}
return (<React.Fragment>
<div>Check</div>
{Children["data"].map(data => <div>map</div>)}
<button
onClick={handleChange}
>Add List</button>
</React.Fragment>);
}
export default Check
try out this I have fixed issues-
import { useState } from "react";
import React from "react";
function Check() {
const [Children, setChildren] = useState({ data: [], otherdata: {} });
function handleChange() {
setChildren({
...Children,
data: [...Children["data"], Children["data"].length],
});
}
return (
<React.Fragment>
<div>Check</div>
{Children.data.map((ele) => (
<div>{ele}</div>
))}
<button onClick={handleChange}>Add List</button>
</React.Fragment>
);
}
export default Check;
For updating your state you must use your state setter, in this case setChildren and not set your state directly (not doing Children["data"] = [...Children["data"], Children["data"].length]).

React useContext Returning Undefined

struggling to with react contexts being used with functional components. I feel like I'm doing everything right here, so any help would be much appreciated.
First I define a context (HeaderHoverContext.js)
import React, { createContext, useState } from "react";
export const HeaderHoverContext = createContext();
export function HeaderHoverProvider(props) {
const [currentHover, setHover] = useState(false);
const toggleHover = (e) => {
setHover(true);
}
return (
<HeaderHoverContext.Provider value={{currentHover, toggleHover}}>
{props.children}
</HeaderHoverContext.Provider>
);
}
I wrap the provider within my header (Header.js)
import React, { Component, useContext } from 'react'
import './header.css'
import Headerbutton from './Headerbutton';
import Hoverviewcontainer from './Hoverviewcontainer'
import {HeaderHoverProvider} from './contexts/HeaderHoverContext'
export default function Header() {
return (
<div className='header'>
<div className='header-right'>
<HeaderHoverProvider>
<Headerbutton text="Misc1" id="misc1" />
<Headerbutton text="Misc2" id="misc2" />
<Hoverviewcontainer id="misc3"/>
<Hoverviewcontainer id="misc4"/>
</HeaderHoverProvider>
</div>
</div>
);
}
Any then lastly, I try to retrieve the context using the useContext hook, but sadly its undefined.
import React, { useContext } from 'react'
import { HeaderHoverContext } from "./contexts/HeaderHoverContext";
export default function Hoverviewcontainer(props) {
const { isHover, setHover } = useContext(HeaderHoverContext);
// Returns undefined
console.log(`Current hover value is ${isHover}`)
return (
<div className={props.isHover ? 'hidden' : 'nothidden'} onMouseEnter={setHover}>
<div className="caret" id={props.id}/>
</div>
)
}
Any ideas what I might be missing here?
The fields in your context aren't called isHover and setHover, they are called currentHover and toggleHover, so either use them in the destructor or destruct manually:
const context = useContext(HeaderHoverContext);
const isHover = context.currentHover;
const setHover = context.toggleHover;
By the way, your toggle hover has a bug, never sets it to false. Try this instead:
const toggleHover = () => setHover(current => !current);

Categories