I am trying to update a textarea's value based on an array. From textToEdit value, on click of show value button I am trying to extract textToEdit's each line and update the view, the when the use effect gets called do some other logic then call setstate again to update the view and then do the someother logic.
In other words, Append each line to textarea and call a function, then append another line, call a function, until all lines are appended.
import React, { useState, useRef, useEffect } from 'react';
function App() {
const [theme, setTheme] = useState('light');
const [language, setLanguage] = useState('javascript');
const [isEditorReady, setIsEditorReady] = useState(false);
const valueGetter = `
some random text line 1
some random text line 2
some random text line 3
some random text line 4
`
const [code, setCode] = useState(valueGetter);
const counts = useRef(0);
const totalCount = useRef(0);
useEffect(() => {
console.log('counts.current', counts.current, totalCount.current);
if (counts.current > 0 && counts.current < totalCount.current) {
counts.current = counts.current + 1;
const stringArr = valueGetter.split(/\n/g);
const newString = stringArr.splice(0, counts.current).join('\n');
// need to do someother logic
setCode(newString);
}
}, []);
function handleShowValue() {
console.log(valueGetter);
counts.current = 1;
const stringArr = valueGetter.split(/\n/g);
totalCount.current = stringArr.length;
const newString = stringArr.splice(0, counts.current).join('\n');
setCode(newString);
}
function toggleTheme() {
setTheme(theme === 'light' ? 'dark' : 'light');
}
function toggleLanguage() {
setLanguage(language === 'javascript' ? 'python' : 'javascript');
}
return (
<>
<button onClick={handleShowValue} disabled={!isEditorReady}>Show value</button>
<textarea
value={code}
/>
</>
);
}
export default App;
This is just adding one line. What am I doing wrong? https://codesandbox.io/s/react-usestate-hook-example-v59wc