Calling a list in a different file in React Native? - javascript

I have two different files currently (file1.jsx and file2.jsx both in the same directory). file2.jsx depends on the list of file1.jsx, so I want to be able to call the list somehow. This is my current implementation.
file1.jsx:
function file1 {
// this is the list I want to call in file2.jsx
const [currentSelection, setCurrentSelection] = uuseState([]);
// also tried export const [currentSelection, setCurrentSelection] = uuseState([]);
...
}
file2.jsx:
//gave me errors
import { currentSelection } from "file1";
function file2 {
...
}
If I can get some help, I would much appreciate it!

State in react-native is internal data-set which affects the rendering of components .It is private and fully controlled by the component .
However if you want to use value of currentSelection in file2 , you can store the value of currentSelection in some central store like redux and then fetch it in file2.

Firstly, you wrote uuseState which should be useState, second for you solution. There are many ways to store an array (assuming that you what to pass to second screen by initial value of your use state is empty array)
You can pass it by react Navigation's params if you are using it,
You can store it using async storage and call that storage on second screen.

Related

My Table is not updating its data with states and useEffect()

I've written a file which contains a Table that should display codes when there are pushed inside the array codes with prop name code (e.x. "848389494")
now every time the function addNewCode is called it should update the _codeData Object but it's not possible because its an outer scouped function. i cant move it inside ScannerResultTable because addNewCode should be able to be exported and used in another Component.
but i dont know how its not possible to useEffect and keep track on "codes" but it wont allow it because it's an outerscouped var.
thanks for your help-
const codes = []
export function addNewCode(value){
codes.push({ code: value });
}
export default function ScannerResultTable() {
const [_codeData, setCodeData] = useState([]);
useEffect(() => {
console.log("Hi im rendering");
setCodeData(codes);
}, []);
const [tableData, setTableData] = useState(_codeData);
Instead of using a globally defined variable codes, you can make use of React context and make the codes a state in some parent components and pass down the utility function to update the codes to the child components that are gonna update it.
More details on how to use react context can be found here

React: Mapping a component with local storage data

I'm currently creating a history list component for a form in a react app and am having some trouble with the local storage.
Essentially, I want the app to render a list of past inputs from the user's local storage data. My current idea is based in duplicating the local storage data is a state variable.
const [history, setHistory] = useState([]);
On form submit I call this function with the form input as the parameter (the input is a single string)
const setLocalStorage = (input) => {
const hist = JSON.parse(localStorage.getItem('history')) || [];
console.log(hist)
hist.push(input)
localStorage.setItem('history', JSON.stringify(hist))
setHistory(hist);
}
This is meant to put the history from local story into hist, push the input that was just submitted into the existing array hist, and update the local storage with the new value. The state variable should then be updated with the most updated array of strings with the setHistory(hist) call.
Also, I want local storage to be pulled on first render so I can use that data to render the history list on initial load. I have a useEffect hook for this as shown:
useEffect(() => {
setHistory(JSON.parse(localStorage.getItem('history')))
console.log(history)
}, []);
The problem I'm facing is that the state never seems to get updated? I can instead do a console log for JSON.parse(localStorage.getItem('history')) and get the local storage array returned but this of course isn't helpful for data usage. I know that the local storage is properly being pulled from this but I'm unable to update the state for some reason. I need the state updated so I can conditionally render and use the array for mapping each item on the history list. When I console log "history" I get an empty array.
TL;DR
Concisely, what is the cleanest method to have local storage and state values maintain equivalency? Hope my post was clear enough to understand!
I'm remaking and updating a regular JS app on React for practice so I'm able to provide a live link of how I want this simple component to work.
https://giovannimalcolm.github.io/weather-dashboard/
The second returned parameter of useState is similar to the this.setState which is asynchronous. You may see that state is not changed even setHistory is called. Passing function instead of the value will avoid this issue as it will be executed after the state is updated. This might be useful for better understanding Passing function to setState()
useEffect(() => {
const hist = JSON.parse(localStorage.getItem('history'))
setHistory(prevHistory => [...prevHistory, ...hist])
}, []);

Can I initialize a useState in a loop?

I use a react module that manages the use of spreadsheets:
react-spreadsheet https://github.com/iddan/react-spreadsheet/
In my project, I need several spreadsheets, and therefore several tables that the user can add, modify, delete on the fly
At the beginning, I wanted to use a big useState variable where the data arrays would be concentrated in the form : stateData = [ [...arrays], [...arrays...] ]
But the module, which uses an OnChange function taking as value the setData, seems to bug when my stateData variable contains different arrays.
<Spreadsheet key={index} className='table' columnLabels={stringLabelCol} rowLabels={stringLabelRow} data={stateData[index]} onChange={setData} />
As I can't manage everything in one UseState with this module,
is it possible to create a series of UseState inside a loop ?
It seems to me that it is a bad practice but I am really blocked
Thank you for reading my text... :/
Seeing your code and your comment, I'm assuming that:
You have one useState named data with ALL your data in it
You have multiple spreadsheets
For each spreadsheet, you want to pass the sheetData and the onChange that updates it
The issue in your code is that you're setting onChange={setData}, meaning any change will override the WHOLE data object, not just the targeted index.
What you want to do is have your onChange function be a function that updates only the right part of your state. So you'd do it like so:
const [data, setData] = useState([])
const updateSheetData = (index, sheetData) => {
// We clone the current state
const tempData = [...data]
// We update the right index
tempData[index] = sheetData
// This is now the new state
setData(tempData)
}
//...
// the onChange function for our component will use our custom function
<Spreadsheet
key={index}
className='table'
columnLabels={stringLabelCol}
rowLabels={stringLabelRow}
data={stateData[index]}
onChange={(newData) => updateSheetData(index, newData)}
/>
Then you'll also have to correctly update the data state whenever you add a new sheet or remove a sheet, to make sure the index are updated. But the idea is the same

reactjs) how can i keep current input value of component when re-render?

I developing front-end with reactjs recently.
but i have a problem in my SPA project.
my webapp have tab menu like a text-editor.
I want each tab to always keep their input value. However, these values are lost because tabs are re-rendering when they disappear or are new.
Is there a way to keep these values without using storage like local-storage?
You will need to take advantage of the useState hook to store an object that contains the data from your tabs... so you can get the data from the object whenever the state changes... assuming you don't update it wrongly.
Find illustratio below:
import React, { useState } from 'react'
function MyTabComponent (props){
const [tabData, updateTabData] = useState({})
return(
// your component jsx here
// you can then fetch your tab data from the tabData object
)
}
Hoping you find this helpful.

Sharing logic in react

I've used higher order component to share a function between my components.With this implementation,the function comes as a prop in my component.The app supports multi languages so in each component a key is passed and the hash value is obtained to display. Hash values are passed to all the components using the context. Now getSkinHash access the context and returns the hash value.
const {getSkinHash} = this.props; //shared function,accesses the context
const value = getSkinHash(SOME_VALUE);
No problem with this implementation but getting the function out of prop every time leads to writing lot's of boilerplate code in all the components.
Is there a better/alternate ways to achieve this?
Thanks
React works with properties, so you can't just say you don't want to work with properties. That is when sharing data between components.
As far as you can do to shorten
const {getSkinHash} = this.props;
const value = getSkinHash(SOME_VALUE);
is to:
this.props.getSkinHash(SOME_VALUE).
If that is a generic function, not component dependent, you can choose to import it into your component just like you import other stuff.
import { myFunction } from './functions'
Then you would simple call it with myFunction.
If you need your function to synchronize data between your components, use a Redux action and connect your components to the global state. Your other components will get to know value hash changes too.

Categories