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);
Related
I am facing a problem with re-rendering after a state change in my NextJS app.
The function sendMessageForm launches a redux action sendMessage which adds the message to the state.
The problem is unrelated to the returned state in the reducer as I am returning a new object(return {...state}) which should trigger the re-render!
Is there anything that might block the re-render ?
This is the file that calls & displays the state, so no other file should be responsible ! But if you believe the problem might lie somewhere else, please do mention !
import { AttachFile, InsertEmoticon, Mic, MoreVert } from '#mui/icons-material';
import { Avatar, CircularProgress, IconButton } from '#mui/material';
import InfiniteScroll from 'react-infinite-scroller';
import Head from 'next/head';
import { useState, useEffect } from 'react';
import Message from '../../components/Message.component';
import styles from '../../styles/Chat.module.css'
import { useRouter } from 'next/router'
import {useSelector, useDispatch} from "react-redux"
import {bindActionCreators} from "redux"
import * as chatActions from "../../state/action-creators/chatActions"
const Chat = () => {
const router = useRouter()
const { roomId } = router.query
const auth = useSelector((state)=> state.auth)
const messages = useSelector((state)=> state.chat[roomId].messages)
const dispatch = useDispatch()
const {getMessages, markAsRead, sendMessage} = bindActionCreators(chatActions, dispatch)
const [inputValue, setInputValue] = useState("")
const sendMessageForm = (e) => {
e.preventDefault()
console.log("***inputValue:", inputValue)
sendMessage(roomId, inputValue)
}
const loadMessages = (page) => {
if(roomId)
getMessages(roomId, page)
}
//user-read-message
useEffect(() => {
//user-read-message
markAsRead(roomId, auth.user._id)
}, [messages]);
return (
<div className={styles.container}>
<Head>
<title>Chat</title>
</Head>
<div className={styles.header}>
<Avatar/>
<div className={styles.headerInformation}>
<h3>Zabre el Ayr</h3>
<p>Last Seen ...</p>
</div>
<div className={styles.headerIcons}>
<IconButton>
<AttachFile/>
</IconButton>
<IconButton>
<MoreVert/>
</IconButton>
</div>
</div>
<div className={styles.chatContainer}>
<InfiniteScroll
isReverse={true}
pageStart={0}
loadMore={loadMessages}
hasMore={messages.hasNextPage || false}
loader={<div className={styles.loader} key={0}><CircularProgress /></div>}
>
{Object.keys(messages.docs).map((key, index)=>{
return<Message
key={index}
sentByMe={messages.docs[key].createdBy === auth.user._id}
message={messages.docs[key].msg}
/>})}
</InfiniteScroll>
<span className={styles.chatContainerEnd}></span>
</div>
<form className={styles.inputContainer}>
<InsertEmoticon/>
<input className={styles.chatInput} value={inputValue} onChange={(e)=>setInputValue(e.target.value)}/>
<button hidden disabled={!inputValue} type='submit' onClick={sendMessageForm}></button>
<Mic/>
</form>
</div>)
};
export default Chat;
useSelector requires a new object with a new reference from the object you are passing to it in order to trigger the re-render
What you're doing with return {...state} is just creating a new object for the parent object but not the nested one useSelector is using, which is in your case :
const messages = useSelector((state)=> state.chat[roomId].messages)
So, you should return the whole state as a new object WITH a new state.chat[roomId].messages object
In other words, the references for the root object & the one being used should be changed.
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]).
I wanna know why will my state remain the same upon rerender of the components.
Here is my parent component
import React, {useEffect} from 'react';
import {connect} from "react-redux"
import NoteList from '../Components/NoteList';
import NoteDetail from '../Components/NoteDetail';
import "./NotePage.scss"
const NotePage = ({note}) => {
const selectNote = (item) => {
if (!item){
return <div className="emptySection"/>
}
console.log("return a new component")
return <NoteDetail/>
}
return (
<div className="NotePage">
<div className="noteList">
<NoteList/>
</div>
<div className="noteDetail">
{selectNote(note)}
</div>
</div>
)
}
const mapState = (state) => (
{
note: state.notesReducer.note
}
)
export default connect(mapState)(NotePage);
I have already checked that this component rerender when the note in redux store changed. The selectNote is executed proper as well. But does it return a brand new component of NoteDetail?
Here is my child component:
import React, {useState, useRef, useEffect} from 'react';
import {connect} from "react-redux";
import Editor from 'draft-js-plugins-editor';
import {EditorState, ContentState} from "draft-js";
import CreateInlineToolbarPlugin from "draft-js-inline-toolbar-plugin";
import CustomInlineToolbar from "./CustomInlineToolbar";
import {updateNote} from "../redux/action"
import "./NoteDetail.scss";
import 'draft-js-inline-toolbar-plugin/lib/plugin.css';
const InlineToolbarPlugin = CreateInlineToolbarPlugin();
const {InlineToolbar} = InlineToolbarPlugin;
const NoteDetail = ({updateNote, title, note, date, _id}) => {
let initContentState = ContentState.createFromText(note);
let [editorState, setEditorState] = useState(EditorState.createWithContent(initContentState));
let [titleState, setTitleState] = useState(title)
let editorRef = useRef(React.createRef());
useEffect(()=>{
updateNote(_id, titleState, editorState)
},[editorState, titleState, _id])
const focus = () => {
editorRef.current.focus()
}
return(
<div>
<div className="NoteDetail-container">
<input type="text" id="title"
value={titleState === "Untitled Page"? "":titleState}
onChange={(e)=>setTitleState(e.target.value)}
/>
<div id="content" onClick={focus}>
<Editor
plugins={[InlineToolbarPlugin]}
onChange={(e)=>setEditorState(e)}
editorState={editorState}
ref={ele => editorRef.current = ele}
/>
<CustomInlineToolbar InlineToolbar={InlineToolbar} />
</div>
</div>
</div>
)
};
const mapProps = (state) => {
const {title, _id, note, date} = state.notesReducer.note
return {
title,
_id,
note,
date
}
}
export default connect (mapProps, {updateNote})(NoteDetail)
It rerenders when the note state changed, but the state remain the same. I checked that the title did change, but the titleState didn't. So how does state and component comparison behave in React?
my reducer:
import {
GET_NOTE,
UPDATE_NOTE,
DEL_NOTE,
CREATE_NOTE,
SELECT_NOTE,
GET_NOTES,
} from "../action/types";
import {
api_getNote,
api_delNote,
api_updateNote,
api_postNote
} from "../../api/noteService"
//TODOS: finish update_title part
const notesReducer = ( state={}, action) => {
switch (action.type){
case GET_NOTES:
return{notes: action.payload}
case UPDATE_NOTE:
const {id, content} = action.payload
api_updateNote(id,content)
return state
case DEL_NOTE:
api_delNote(action.payload)
return state
case CREATE_NOTE:
api_postNote(action.payload, (res)=> {
return {notes: res}
})
return state
case SELECT_NOTE:
return {...state, note: action.payload}
default:
return state
}
}
export default notesReducer
I've set up my context and I have a function that runs once the form is submitted handleSubmit. When I submit the form, I want the results to be shown on a separate page dashboard. I'm using history.push().
My form is wrapped in the withRouter HOC.
When I submit the form, I receive "props.history is undefined"
I also have another function that is using a match.params and I'm getting undefined as well. So I'm assuming it has to do with React Router.
I considered that perhaps my Context file is the one that needs to be wrapped with the withRouter HOC, but the file has two exports.
My Context Provider
import React, { useState, useEffect, createContext } from 'react'
const AnimeContext = createContext()
const API = "https://api.jikan.moe/v3"
const AnimeProvider = (props) => {
const urls = [
`${API}/top/anime/1/airing`,
`${API}/top/anime/1/tv`,
`${API}/top/anime/1/upcoming`,
]
// State for Anime search form
const [dataItems, setDataItems] = useState([])
const [animeSearched, setAnimeSearched] = useState(false)
// Fetch searched Anime
async function handleSubmit(e) {
e.preventDefault()
const animeQuery = e.target.elements.anime.value
const response = await fetch(`${API}/search/anime?q=${animeQuery}&page=1`)
const animeData = await response.json()
setDataItems(animeData.results)
setAnimeSearched(!animeSearched)
props.history.push('/dashboard')
}
return (
<AnimeContext.Provider value={{
topTv,
setTopTv,
topAiring,
setTopAiring,
topUpcoming,
setTopUpcoming,
dataItems,
setDataItems,
animeSearched,
setAnimeSearched,
fetching,
anime,
fetchTopAnime,
fetchAnimeDetails,
handleSubmit
}}>
{props.children}
</AnimeContext.Provider>
)
}
export { AnimeProvider, AnimeContext }
My SearchForm component
import React, { useContext } from 'react';
import { withRouter } from 'react-router-dom'
import styled from 'styled-components'
import AnimeCard from './AnimeCard/AnimeCard';
import { AnimeContext } from '../store/AnimeContext'
const SearchForm = () => {
const { dataItems, animeSearched, handleSubmit } = useContext(AnimeContext)
return (
<div>
<Form onSubmit={handleSubmit}>
<Input
type="text"
name="anime"
placeholder="Enter title"
/>
<FormButton type='submit'>Search</FormButton>
</ Form>
{animeSearched
?
<AnimeCard
dataItems={dataItems}
/>
: null}
</div>
)
}
export default withRouter(SearchForm)
you can always use useHitory hook everywhere!
import { useHistory } from 'react-router'
...
const Page = function(props) {
let history = useHistory();
...
history.push('/')
...
}
In react-router, you would get history from props if any component is rendered as a child or Route or from an ancestor that is renderd form Route and it passed the Router props to it. However it is not receiving Router props, i suggest try this one
You can use Redirect from react-router-dom
import { Redirect } from "react-router-dom";
const [redirect, setRedirect] = useState(false);
Now set the vlue of redirect to true where ever you want
setRedirect(true);
like in your case
async function handleSubmit(e) {
e.preventDefault()
const animeQuery = e.target.elements.anime.value
const response = await fetch(`${API}/search/anime?q=${animeQuery}&page=1`)
const animeData = await response.json()
setDataItems(animeData.results)
setAnimeSearched(!animeSearched)
setRedirect(true);
}
Now you can use the following for the Redirection in return function like so
if(redirect) {
return <Redirect to="/dashboard" />
} else {
return (
<Your-Component />
)
Below is the code for my biggest nightmare yet. I keep on getting the error that the apiData.map is not a function. Any body that can help please.
I also need to know why ApiGetData do not use react please.
I do get the api data but seems that I'm importing it incorrectly to ClassFilmData and I get the .map error. All help will be appreciated.
Tried to export films, ApiGetData in various way. Help received from other platforms was implemented but did not solve the problem. Searches - other swapi projects, import data react, sandbox, repo and other platforms
// import React from 'react';
import { ApiToGet } from "./ApiToGet";
const ApiGetData = async function() {
try {
const films = await Promise.all(
ApiToGet.map(url => fetch(url).then(resp => resp.json()))
);
console.log("film title - ", films.results);
return films;
} catch (err) {
console.log("oooooooops", err);
}
};
ApiGetData();
export default ApiGetData;
import React from "react";
import FilmsInfo from "./FilmsInfo";
const FilmsLoop = ({ apiData }) => {
return (
<div className="tc f1 unknown">
{apiData.map((answers, i) => {
return (
<FilmsInfo
key={i}
// title={ apiData.films.results[i].title }
/>
);
})}
</div>
);
};
export default FilmsLoop;
import React, { Component } from "react";
import FilmsLoop from "./FilmsLoop";
import ApiGetData from "./ApiGetData";
class ClassFilmData extends Component {
render() {
return (
<div>
<p className="tc f1">Wim - classfilmdata</p>
<FilmsLoop apiData={ApiGetData} />
</div>
);
}
}
export default ClassFilmData;
import React from "react";
const FilmsInfo = () => {
return (
<div className="tc bg-light-blue dib br3 pa3 ma3 grow bw2 shadow-5">
<p>Planet</p>
<p>FilmsInfo.js</p>
</div>
);
};
export default FilmsInfo;
That is because apiData is really ApiGetData which is a promise.
If you're trying to use the array returned by resolving this promise, you'll have to do something like this:
class ClassFilmData extends Component {
componentDidMount() {
const apiData = await ApiGetData();
this.setState({ apiData });
}
render() {
return(
<div>
<p className="tc f1">Wim - classfilmdata</p>
{this.state.apiData && <FilmsLoop apiData={ this.state.apiData }/> }
</div>
);
}
}