Reputation: 310
I have two pages:
When tapping on an item in the list on Page1, you are taken to Page2 where you can update the counter value. Simple.
But I can't for the life of me figure out why the counter value in the list on Page1 isn't updating when updating the value on Page2.
Below is my code. I've left out irrelevant lines like styles, etc.
Here is my Store
:
class RecordStore {
data: any[] = [];
constructor() {
makeAutoObservable(this);
}
// Get the list data from backend
getRecordData = async() => {
try {
const response = await postRequest('record/get');
const json = response.data;
const records = json.records;
this.setData(records);
} catch(error) {
console.log(error);
}
};
// Set the data
setData = (data: any) => {
this.data = data;
};
// Used to update a single record in the data, matching the IDs
updateRecord = (record: any) => {
const result = this.data.map((item) => item.id === record.id ? record : item);
}
}
// Instantiate the counter store.
const counterStore = new RecordStore();
// Create a React Context with the counter store instance.
export const CounterStoreContext = React.createContext(counterStore);
export const useRecordStore = () => React.useContext(CounterStoreContext)
Here is Page1
:
const TabTwoScreen = observer(() => {
const { data, getRecordData } = useRecordStore();
useEffect(() => {
// Get the record data to populate the list
getRecordData();
}, []);
return (
<SafeAreaView>
<View>
<FlatList
data={data}
renderItem={({item}) => {
return (
<Observer>
{() =>
<Link
href={{
pathname: "/record",
params: { recordId: item.id }
}} asChild>
<Pressable>
<View>
<Text>{item.counter}</Text>
</View>
</Pressable>
</Link>
}
</Observer>
)
}}
/>
</View>
</SafeAreaView>
);
});
export default TabTwoScreen;
And here is Page2
:
const Record = observer(() => {
const { updateRecord } = useRecordStore();
// Submit the updated record to the API
// API returns the record's json
const onSubmit = async () => {
try {
const response = await postRequest('record/update', { recordId: record?.id, counter: counter });
const json = response.data;
const jsonRecord = JSON.stringify(json.data);
// Update the Store record
updateRecord(jsonRecord);
} catch(error) {
console.log(error);
}
}
return (
// Simply shows a text field and a submit button
);
});
export default Record;
What am I doing wrong that's causing the List item to not show the updated count when I go back from Page2 to Page1?
Thanks
Upvotes: 1
Views: 24