I have a functional component built around the React Table component that uses the Apollo GraphQL client for server-side pagination and searching. I am trying to implement debouncing for the searching so that only one query is executed against the server once the user stops typing with that value. I have tried the lodash debounce and awesome debounce promise solutions but still a query gets executed against the server for every character typed in the search field.
Here is my component (with irrelevant info redacted):
import React, {useEffect, useState} from 'react';
import ReactTable from "react-table";
import _ from 'lodash';
import classnames from 'classnames';
import "react-table/react-table.css";
import PaginationComponent from "./PaginationComponent";
import LoadingComponent from "./LoadingComponent";
import {Button, Icon} from "../../elements";
import PropTypes from 'prop-types';
import Card from "../card/Card";
import './data-table.css';
import debounce from 'lodash/debounce';
function DataTable(props) {
const [searchText, setSearchText] = useState('');
const [showSearchBar, setShowSearchBar] = useState(false);
const handleFilterChange = (e) => {
let searchText = e.target.value;
setSearchText(searchText);
if (searchText) {
debounceLoadData({
columns: searchableColumns,
value: searchText
});
}
};
const loadData = (filter) => {
// grab one extra record to see if we need a 'next' button
const limit = pageSize + 1;
const offset = pageSize * page;
if (props.loadData) {
props.loadData({
variables: {
hideLoader: true,
opts: {
offset,
limit,
orderBy,
filter,
includeCnt: props.totalCnt > 0
}
},
updateQuery: (prev, {fetchMoreResult}) => {
if (!fetchMoreResult) return prev;
return Object.assign({}, prev, {
[props.propName]: [...fetchMoreResult[props.propName]]
});
}
}).catch(function (error) {
console.error(error);
})
}
};
const debounceLoadData = debounce((filter) => {
loadData(filter);
}, 1000);
return (
<div>
<Card style={{
border: props.noCardBorder ? 'none' : ''
}}>
{showSearchBar ? (
<span className="card-header-icon"><Icon className='magnify'/></span>
<input
autoFocus={true}
type="text"
className="form-control"
onChange={handleFilterChange}
value={searchText}
/>
<a href="javascript:void(0)"><Icon className='close' clickable
onClick={() => {
setShowSearchBar(false);
setSearchText('');
}}/></a>
) : (
<div>
{visibleData.length > 0 && (
<li className="icon-action"><a
href="javascript:void(0)"><Icon className='magnify' onClick= {() => {
setShowSearchBar(true);
setSearchText('');
}}/></a>
</li>
)}
</div>
)
)}
<Card.Body className='flush'>
<ReactTable
columns={columns}
data={visibleData}
/>
</Card.Body>
</Card>
</div>
);
}
export default DataTable
... and this is the outcome: link
debounceLoadData will be a new function for every render. You can use the useCallback hook to make sure that the same function is being persisted between renders and it will work as expected.
useCallback(debounce(loadData, 1000), []);
const { useState, useCallback } = React;
const { debounce } = _;
function App() {
const [filter, setFilter] = useState("");
const debounceLoadData = useCallback(debounce(console.log, 1000), []);
function handleFilterChange(event) {
const { value } = event.target;
setFilter(value);
debounceLoadData(value);
}
return <input value={filter} onChange={handleFilterChange} />;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
To add onto Tholle's answer: if you want to make full use of hooks, you can use the useEffect hook to watch for changes in the filter and run the debouncedLoadData function when that happens:
const { useState, useCallback, useEffect } = React;
const { debounce } = _;
function App() {
const [filter, setFilter] = useState("");
const debounceLoadData = useCallback(debounce(fetchData, 1000), []);
useEffect(() => {
debounceLoadData(filter);
}, [filter]);
function fetchData(filter) {
console.log(filter);
}
return <input value={filter} onChange={event => setFilter(event.target.value)} />;
}
ReactDOM.render(<App />, document.getElementById("root"));
You must remember the debounced function between renders.
However, you should not use useCallback to remember a debounced (or throttled) function as suggested in other answers. useCallback is designed for inline functions!
Instead use useMemo to remember the debounced function between renders:
useMemo(() => debounce(loadData, 1000), []);
I hope this post will get you to the solution ,
You don't have to use external library for Debouncing you can create your own custom hook follow my steps
step(1):- Create the custom hook of Debouncing
import { useEffect ,useState} from 'react';
export const UseDebounce = (value,delay)=>{
const [debouncedValue,setDebouncedValue]= useState();
useEffect(()=>{
let timer = setTimeout(()=>setDebouncedValue(value),delay)
return ()=> clearTimeout(timer);
},[value])
return debouncedValue
}
step(2) :- Now create the file in which you want to add throttle
import React from 'react'
import { useEffect } from 'react';
import { useState } from 'react';
import {UseDebounce} from "./UseDebounce";
function Test() {
const [input, setInput] = useState("");
const debouncedValue = UseDebounce(input,1000);
const handleChange = (e)=>{
setInput(e.target.value)
}
useEffect(()=>{
UseDebounce&& console.log("UseDebounce",UseDebounce)
},[UseDebounce])
return (
<div>
<input type="text" onChange={handleChange} value={input}/>
{UseDebounce}
</div>
)
}
export default Test;
NOTE:- To test this file first create react app then embrace my files in it
Hope this solution worthwhile to you
Related
I'm writing React functional component that should be input for search on Neo4j.
I'm dependant on the useReadCypher and cannot change it's inner implementation.
I cannot write the useReadCypher inside the useEffect because it's break the rule of hooks.
import React, { useState, useEffect, useCallback } from 'react';
import { useReadCypher } from "use-neo4j";
export default function Search() {
const [count, setCount\] = useState(0);
const [runQuery, setRunQuery\] = useState(false);
const query = `MATCH (n) RETURN n LIMIT ${count}`;
const data = useReadCypher(query);
const handleClick = useCallback(() => {
setCount(count + 1);
setRunQuery(true);
}, [count]);
useEffect(() => {
if (runQuery) {
console.log('Data changed', data);
setRunQuery(false);
}
}, [data, runQuery]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
{JSON.stringify(data)}
</div>
);
}
I want to be able to click on the button to rerun the query using the useReadCypher.
What should be the approach to solving this issue?
Thank you.
It was the solution. Here is my final component.
import React, { useState, useEffect, useCallback } from 'react';
import { useReadCypher } from "use-neo4j";
import {Header} from "semantic-ui-react";
import {StyledDiv, StyledInput} from "./Style";
export default function Search() {
const [term, setTerm] = useState('');
const [runQuery, setRunQuery] = useState(false);
const query = `MATCH (n) RETURN n LIMIT ${term}`;
const {records, run} = useReadCypher(query);
const handleClick = useCallback(() => {
setRunQuery(true);
run();
}, [term]);
useEffect(() => {
if (runQuery) {
console.log('Data changed', records);
setRunQuery(false);
}
}, [records, runQuery]);
return (
<>
<Header as='H2' color='blue' textAlign='center' block>Search</Header>
<StyledDiv>
<StyledInput
value={term}
onChange={(e: any) => setTerm(e.target.value)}
/>
<button onClick={handleClick}>Search</button>
</StyledDiv>
<div>
{JSON.stringify(records)}
</div>
</>
);
}
Code sandbox link: https://codesandbox.io/s/useinterval-customhook-iucj8q?file=/src/components/Displaytimer.js
I have created a custom hook for clock countdown while I am passing minutes input field values and seconds input fields as a prop to the child component it is taking the values too but when I click the start button it is still showing the 0. I think this is taking initial values I have used promises too and console logging each and every value but no use.
Image for output:
APP.js
import "./styles.css";
import Timer from "./components/Timer";
export default function App() {
return (
<div className="App">
<Timer />
</div>
);
}
Timer.js
import { useState, useRef } from "react";
import DisplayTimer from "./Displaytimer";
export default function Timer() {
const [min, setMins] = useState(0);
const [sec, setSecs] = useState(0);
const refValueMinutes = useRef();
const refValueSeconds = useRef();
const onchangeMinutes = (e) => {
// refValueMinutes.current = Number(e.target.value);
// const currVal = refValueMinutes.current;
setMins(Number(e.target.value));
};
const onchangeSeconds = (e) => {
// refValueSeconds.current = Number(e.target.value);
// const currVal = refValueSeconds.current;
setSecs(Number(e.target.value));
};
return (
<div>
<h2>Minutes: </h2> <br />
<input onChange={onchangeMinutes} />
<h2>Seconds: </h2> <br />
<input onChange={onchangeSeconds} />
<br />
<br />
<DisplayTimer min={min} sec={sec} />
</div>
);
}
enter image description here
UseInterval.js(custom hook)
import { useRef, useEffect } from "react";
export default function UseInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => {
clearInterval(id);
};
}
}, [delay]);
}
I thought this is due to DOM painting to the web page before the values get initiated to the state so I have tried using promises but no result and suggest me a good way to render this design to the webpage.
I have used use effect too:
useEffect(() => {
startTime();
stopTime();
resetTime();
}, []);
I'm creating a counter state using useState and useRef. However I'm getting this error
Here's my code
import { useEffect, useRef, useState} from 'react';
const App = () => {
const [clicks, setClick] = useState(0)
const myComponentDiv = useRef(null)
useEffect(() => {
if (myComponentDiv && myComponentDiv.current) {
myComponentDiv.current.addEventListener('click', clickHandler)
return () => {
myComponentDiv.current.removeEventListener('click', clickHandler)
}
}
}, [myComponentDiv]);
const clickHandler = () => {
setClick(clicks + 1)
}
return (
<div className="App">
<div className="my-component" ref="myComponentDiv">
<h2>My Component {clicks} clicks</h2>
</div>
</div>
);
}
export default App;
May i know where i did wrong?
Here:
ref="myComponentDiv"
should be:
ref={myComponentDiv}
I am trying to get a value from the code mirror input field but I don't know why I am not getting the value from code mirror input field
import CodeMirror from "#uiw/react-codemirror";
import { markdown, markdownLanguage } from "#codemirror/lang-markdown";
import { languages } from "#codemirror/language-data";
export default function Editor() {
const [get, set] = useState("");
console.log(get); {/* doesn't display anything */}
return (
<>
<CodeMirror
value={get}
extensions={[
markdown({ base: markdownLanguage, codeLanguages: languages }),
]}
onInput={(e) => set(e.target.value)}
/>
</>
);
}
Try useEffect hook, it calls the function inside whenever variable in second argument array changes, in this specific scenario when get changes.
import CodeMirror from "#uiw/react-codemirror";
import { markdown, markdownLanguage } from "#codemirror/lang-markdown";
import { languages } from "#codemirror/language-data";
import { useEffect } from "react";
export default function Editor() {
const [get, set] = useState("");
useEffect(() => {
console.log(get) //gets called whenever get state changes
}, [get])
return (
<>
<CodeMirror
value={get}
extensions={[
markdown({ base: markdownLanguage, codeLanguages: languages }),
]}
onInput={(e) => set(e.target.value)}
/>
</>
);
}
The onChange handler can output the value as below.
import { markdown, markdownLanguage } from "#codemirror/lang-markdown";
import { languages } from "#codemirror/language-data";
import { useState } from "react";
export default function Editor() {
const [get, set] = useState("");
console.log(get);
return (
<>
<CodeMirror
value={get}
extensions={[
markdown({ base: markdownLanguage, codeLanguages: languages })
]}
onChange={(value) => set(value)}
/>
</>
);
}
Working example
I have been trying to get draft js mention plugin to work with react hooks but can't seem to figure what's wrong with the code. Appreciate any help on this.
import React, { useRef, useState, useEffect } from "react";
import { EditorState } from "draft-js";
import Editor from "draft-js-plugins-editor";
import createMentionPlugin, { defaultSuggestionsFilter } from "draft-js-mention-plugin";
import mentions from "./mentions";
export default function MentionEditor() {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const [suggestions, setSuggestions] = useState(mentions);
const editor = useRef(null);
useEffect(() => {
editor.current.focus();
}, [])
const mentionPlugin = createMentionPlugin();
const { MentionSuggestions } = mentionPlugin;
const plugins = [mentionPlugin];
const onSearchChange = ({ value }) => {
setSuggestions(defaultSuggestionsFilter(value, mentions))
};
return (
<div style={{ border: "1px solid gray" }}>
<Editor
editorState={editorState}
onChange={editorState => setEditorState(editorState)}
plugins={plugins}
ref={editor}
/>
<MentionSuggestions
onSearchChange={onSearchChange}
suggestions={suggestions}
/>
</div>
);
}
You need to move the draft-js plugin configuration outside the component arrow function. This is a pretty basic Draft-JS implementation using a functional component and hooks:
import React, { useState, useRef } from 'react'
import { EditorState } from 'draft-js'
import Editor from 'draft-js-plugins-editor'
import createMentionPlugin, { defaultSuggestionsFilter } from 'draft-js-mention-plugin'
import 'draft-js/dist/Draft.css'
import 'draft-js-mention-plugin/lib/plugin.css'
import mentions from "./mentions"
// Draft-JS-Mentions plugin configuration
const mentionPlugin = createMentionPlugin()
const { MentionSuggestions } = mentionPlugin
const plugins = [mentionPlugin]
const MyEditor= () => {
const [suggestions, setSuggestions] = useState(mentions)
// Draft-JS editor configuration
const [editorState, setEditorState] = useState(
() => EditorState.createEmpty(),
)
const editor = useRef(null)
// Check editor text for mentions
const onSearchChange = ({ value }) => {
setSuggestions(defaultSuggestionsFilter(value, mentions))
}
const onAddMention = () => {
}
// Focus on editor window
const focusEditor = () => {
editor.current.focus()
}
return (
<div onClick={() => focusEditor()}>
<Editor
ref={editor}
editorState={editorState}
plugins={plugins}
onChange={editorState => setEditorState(editorState)}
placeholder={'Type here...'}
/>
<MentionSuggestions
onSearchChange={onSearchChange}
suggestions={suggestions}
onAddMention={onAddMention}
/>
</div>
)
}
export default MyEditor
Just move these lines outside component and it will work:
const mentionPlugin = createMentionPlugin();
const { MentionSuggestions } = mentionPlugin;
const plugins = [mentionPlugin];
export default function MentionEditor() {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
.. ... ...
}
!!!!!!!!!!!!!!!! PAY ATTENTION !!!!!!!!!!!!
The onSearchChange method will be triggered once the '#' character is typed, so in this case it will return just 5 items that fit the empty string...
To prevent this to be happened, just check that the value we want to search is not empty:
const onSearchChange = ({ value }) => {
if (value) {
setSuggestions(defaultSuggestionsFilter(value, mentions));
}
};