i get data from server by useReducer and do some action on that and showing them on table and for that i use .filter() but it gives me an Error that my data is Undefined
this is my UseReducer :
function savedEventsReducer(state, { type, payload }) {
switch (type) {
case "push":
return [...state, payload];
case "update":
return state.map((evt) =>
evt.id === payload.id ? payload : evt
);
case "delete":
return state.filter((evt) => evt.id !== payload.id);
default:
throw new Error();
}
}
const [SavedEvents, dispatchcallEvent] =
useReducer(savedEventsReducer, [])
useEffect(() => {
axios.get('http://localhost:8000/SavedEvents/').then(resp => {
dispatchcallEvent({ type: 'push', payload: resp.data });
})
}, [])
this is my actions functions that filter my data :
const [Lables, SetLables] = useState([])
const filteredEvents = useMemo(() => {
if(SavedEvents[0]){
console.log(SavedEvents[0]); // it's gives me my Data and not Undefine.
console.log(SavedEvents);
return SavedEvents[0].filter((evt) => // this is the line that mentioned in Error
Lables
.filter((lbl) => lbl.checked)
.map((lbl) => lbl.label)
.includes(evt.label)
);}
}, [SavedEvents, Lables])
useEffect(() => {
SetLables((prevLabels) => {
if(SavedEvents[0]){
return [...new Set(SavedEvents[0].map((evt) => evt.label))].map(
(label) => {
const currentLabel = prevLabels.find(
(lbl) => lbl.label === label
);
return {
label,
checked: currentLabel ? currentLabel.checked : true,
};
}
);
}
});
}, [SavedEvents])
all this Codes are in my Context and i use them and after first render all of them are render
this is My whole Error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'filter')
at ContextWrapper.js:58:1
at Array.filter (<anonymous>)
at ContextWrapper.js:58:1
at updateMemo (react-dom.development.js:15867:1)
at Object.useMemo (react-dom.development.js:16413:1)
at useMemo (react.development.js:1532:1)
at ContextWrapper (ContextWrapper.js:54:1)
this is SavedEvents[0] :
you should add another condition on top of your SetLables Like :
useEffect(() => {
if(SavedEvents[0]){
SetLables((prevLabels) => {
// console.log(SavedEvents[0]);
return [...new Set(SavedEvents[0].map((evt) => evt.label))].map(
(label) => {
const currentLabel = prevLabels.find(
(lbl) => lbl.label === label
);
return {
label,
checked: currentLabel ? currentLabel.checked : true,
};
}
);
});
}
// console.log(Lables);
}, [SavedEvents])
The purpose of this application is to make an API call to google places API, gather info about a restaurant, then display to the user.
The application works for the most part but every maybe 5-10 API calls on average the app crashes.
The error:
The code:
// State and global variables //
const [searchResponse, setSearchResponse] = useState("");
const [secondarySearchResponse, setsecondarySearchResponse] = useState("");
const [information, setInformation] = useState("");
const [secondaryInformation, setSecondaryInformation] = useState("");
const [itemFilter, setFilter] = useState("");
const [place_id, setPlaceId] = useState("");
const [dataReady, setDataReady] = useState(false);
const [locationHad, setLocationHad] = useState(false);
const pos = useRef(null);
const key = "AIzaSyD1ZTsmbDBBlMpmaogO_hlj93zzbDDtAoc";
var num = Math.floor(Math.random() * 20 + 1);
// Use Effects
// Gets users current location
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
pos.current = position;
console.log("Location had. Ready for API call.");
setLocationHad(true);
});
}, []);
// Once we have clicked our button and made our api call, we get the place_id and save it so we can make a secondary api call using place_id
useEffect(() => {
if (
searchResponse !== "" &&
searchResponse.results[num].place_id !== undefined) {
setPlaceId(searchResponse.results[num].place_id);
console.log("place_id set");
} else {
console.log("error in setting place_id");
}
}, [searchResponse]);
// One place_id is set we make secondary api call
useEffect(() => {
if (place_id !== "") {
fetchSecondaryInfo();
} else {
console.log("no place id!");
}
}, [place_id]);
// Now that we have made both api calls we save the relavent info into state that we will pass down to child components
useEffect(() => {
if (searchResponse !== "") {
console.log(searchResponse.results[num].name);
setInformation({
name: searchResponse.results[num].name,
open_now: searchResponse.results[num].opening_hours.open_now,
rating: searchResponse.results[num].rating,
price: searchResponse.results[num].price_level,
location: {
lat: searchResponse.results[num].geometry.location.lat,
lng: searchResponse.results[num].geometry.location.lng,
},
});
console.log("info set!");
} else {
console.log("no info to set!");
}
}, [searchResponse]);
// And again for the secondary info (I broke this dwown into to seperate useEffects trying to figure out what was causing my error...)
useEffect(() => {
if (secondarySearchResponse !== "") {
setSecondaryInformation({
phone_number: secondarySearchResponse.result.formatted_phone_number,
daily_hours: secondarySearchResponse.result.opening_hours.weekday_text,
address: secondarySearchResponse.result.formatted_address,
});
setDataReady(true);
console.log("secondary info set!");
} else {
console.log("no secondary info to set!");
}
}, [secondarySearchResponse]);
// Function that makes api call
async function fetchInfo() {
if (locationHad) {
if (itemFilter === "") {
var url = `https://secure-dawn-88985.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${pos.current.coords.latitude},${pos.current.coords.longitude}&radius=12000&type=restaurant&key=${key}`;
} else {
var url = `https://secure-dawn-88985.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=${itemFilter[0]}&location=${pos.current.coords.latitude},${pos.current.coords.longitude}&radius=12000&type=restaurant&key=${key}`;
}
await fetch(url)
.then((response) => response.json())
.then((data) => setSearchResponse(data))
.then(console.log("api request fired."));
} else {
console.log("location not yet identified!");
}
}
// Function that makes secondary api call
async function fetchSecondaryInfo() {
if (place_id !== "") {
const secondary_url = `https://secure-dawn-88985.herokuapp.com/https://maps.googleapis.com/maps/api/place/details/json?fields=formatted_phone_number,opening_hours,formatted_address&place_id=${place_id}&key=${key}`;
await fetch(secondary_url)
.then((response) => response.json())
.then((data) => setsecondarySearchResponse(data))
.then(console.log("secondary api request fired."));
} else {
console.log("place_id not had in secondary fetch.");
}
}
As for the place_id error I put in the a specific line of code to avoid this error:
useEffect(() => {
if (
searchResponse !== "" &&
searchResponse.results[num].place_id !== undefined
) {
console.log(searchResponse.results[num].place_id);
setPlaceId(searchResponse.results[num].place_id);
console.log("place_id set");
} else {
console.log("error in setting place_id");
}
}, [searchResponse]);
So I do not understand how its possible to even throw this error with that line in there.
As for the name error I put in a specific line to console log the object before it reads the properties but it doesn't print in the console before throwing the error:
useEffect(() => {
if (searchResponse !== "") {
console.log(searchResponse.results[num].name);
setInformation({
name: searchResponse.results[num].name,
open_now: searchResponse.results[num].opening_hours.open_now,
rating: searchResponse.results[num].rating,
price: searchResponse.results[num].price_level,
location: {
lat: searchResponse.results[num].geometry.location.lat,
lng: searchResponse.results[num].geometry.location.lng,
},
});
console.log("info set!");
..........
I appreciate any input, suggestions, critiques, etc.
The error message shows that the error is being thrown on this line:
searchResponse.results[num].place_id !== undefined
This will throw if searchResponse.results[num] doesn't exist.
To be concise, try using optional chaining (and initialize searchResponse to undefined or null). Do
const [searchResponse, setSearchResponse] = useState();
and change
if (
searchResponse !== "" &&
searchResponse.results[num].place_id !== undefined) {
setPlaceId(searchResponse.results[num].place_id);
to
const possiblePlaceId = searchResponse?.results[num]?.place_id;
if (possiblePlaceId) {
setPlaceId(possiblePlaceId);
A button calls the function signAllBrowsed, which contains two other functions:
loadSafetyLetters is a hook that makes a database call for some data and sets it in context
signAll is a hook that tries to access data in context to do something with it
Context is getting set properly, but when signAll accesses it, the data is not updated. Is there a way to access the updated context without directly passing it to the 2nd function? Or is there a way to call a callback once context is updated and accessible? Seems the updated context is only available after a re-render.
The component containing signAllBrowsed and the 2 hooks are siblings.
code in above image:
setModalVisible(true)
const logHeader = 'SafetyLetterHome::SignAllBrowsed'
try {
const response = await loadSafetyLetters(false) // before beginning sign all, get a fresh list of letters from db
if (Configs.SHOW_REQUEST_LOGS) console.log(`${logHeader} response`, response)
if (response === 'no api error') {
await signAll()
navigation.navigate('SafetyLetterSign')
}
} catch (error) {
const errorMessage = error.status && error.status.message ? error.status.message : error
Alert.alert('Database Error', errorMessage)
console.log(`${logHeader}`, errorMessage)
}
}
loadSafetyLetters calls the loadLetters hook:
const [getLetters] = useGetLetters()
const [sortLetters] = useSortLetters()
const [hasAPIError] = useHasAPIError()
const navigation = useNavigation()
const { setModalVisible, setShowSignAll, setSortedLetters, setUnsortedLetters } = useContext(SafetyContext)
const loadLetters = async (sort = true) => {
try {
const response = await getLetters()
const logHeader = 'SafetyHome::loadLetters'
const errorMessage = 'The following error occurred when trying to load letters:'
if (Configs.SHOW_REQUEST_LOGS) console.log(`${logHeader} response`, response)
const error = hasAPIError(response, logHeader, errorMessage)
if (error) return error
const { data } = response.data.payload
let unsortedLetters = []
if (data !== null && data.length > 0) {
data.map((item) => {
// grab only unsigned letters
if (
item.assignmentStatus === SafetySources.PENDING ||
item.assignmentStatus === SafetySources.BROWSED ||
item.assignmentStatus === SafetySources.QUESTIONS_COMPLETE
) {
unsortedLetters.push({
safetyLetterId: item.safetyLetterId,
title: item.title,
assignmentStatus: item.assignmentStatus,
filePath: item.filePath,
embeddableToken: item.embeddableToken,
sponsorId: item.sponsorId,
letterDate: item.letterDate,
form16: item.form16Enabled === '1' ? true : false,
sponsorName: item.sponsorName,
type: item.letterType,
sortOrder: item.sortOrder, // dear doctor; sortOrder === 1
})
}
})
}
if (unsortedLetters.length > 0) {
let bletters = unsortedLetters.filter((letter) => letter.assignmentStatus === SafetySources.BROWSED || letter.assignmentStatus === SafetySources.QUESTIONS_COMPLETE)
console.log('useLoadLetters; setting fresh pull of letters in context, including ', bletters.length, ' browsed letters')
setUnsortedLetters(unsortedLetters) // set in context
setShowSignAll( // show/hide sign all button
unsortedLetters.some((letter) =>
letter.assignmentStatus === SafetySources.BROWSED ||
letter.assignmentStatus === SafetySources.QUESTIONS_COMPLETE,
))
}
if (sort) {
if (unsortedLetters.length > 0) {
let sortedLetters = sortLetters(unsortedLetters) // sort letters with hook
setSortedLetters(sortedLetters) // set in context
}
}
} catch (error) {
console.log('SafetyHome::loadLetters ', error)
const errorMessage = error.status && error.status.message ? error.status.message : error
Alert.alert(
'Error Loading Letters',
`A database error has occurred. Please try again. (${errorMessage})`,
)
navigation.navigate('Home')
} finally {
setModalVisible(false)
}
}
return [loadLetters]
}
signAll hook:
const { state: { unsortedLetters },
setF16Browsed,
setQcAndBrowsed,
setModalVisible,
setSelectedLetter
} = useContext(SafetyContext)
const signAll = async () => {
let qcAndBrowsed = [] // set letter groups in context
let f16Browsed = []
unsortedLetters.forEach((letter) => {
if (
letter.assignmentStatus === SafetySources.BROWSED ||
letter.assignmentStatus === SafetySources.QUESTIONS_COMPLETE
) {
if (
letter.form16 &&
letter.assignmentStatus !== SafetySources.QUESTIONS_COMPLETE
) {
f16Browsed.push(letter)
} else {
qcAndBrowsed.push(letter)
}
}
})
setQcAndBrowsed(qcAndBrowsed)
setF16Browsed(f16Browsed)
// begin sign all with first f16 letter
if (f16Browsed.length > 0) {
setSelectedLetter(f16Browsed[0])
} else {
setSelectedLetter(null) // clear any previous viewed letter
}
setModalVisible(false)
}
return [signAll]
}
I want to add an All Option to my existing select box.
Select box is creating with some API data. With the API data set I want to add an ALL option above.
This is my code.
const useChemicals = () => {
const [data, setData]: any = useState([]);
useEffect(() => {
const getChemicalsData = async () => {
try {
const results = await searchApi.requestChemicalsList();
if (results.data) {
let groupCount = 0;
const chemList: any = [];
results.data.data.chemicals.map((chemical: any, index: number) => {
if (chemical.key === '') {
chemList.push({
label: chemical.value,
options: [],
});
}
});
results.data.data.chemicals.map((chemical: any, index: number) => {
if (chemical.key === '') {
if (index > 1) {
groupCount += 1;
}
} else {
chemList[groupCount].options.push({
label: chemical.value,
value: chemical.key,
});
}
});
setData([...chemList]);
}
} catch (e) {}
};
getChemicalsData();
}, []);
return data && data;
};
export default useChemicals;
How can I add this. Please help me, I am new to React.
I am running a React application.
When I enter the page through routes(click button or link) page works fine but when I reload the page it crashes. I cannot see where the error is, the console and source show just blank, this is the server message console message.
server: Entrypoint index [big] = index.js index.1af9d975ff74be4d27d9.hot-update.js index.c93bf08301ec20c0dc85.js.map index.c93bf08301ec20c0dc85.js.map
server: 533 modules
server: backend debug read session { csrfToken: '0ae87c36d850008df20b58941bf89072', id: 2 }
server: backend debug {"data":{"currentUser":null}} <= undefined
server: backend debug {"data":{"currentUser":null}} <= undefined
server: backend debug read session {}
server: backend error TypeError: Cannot convert undefined or null to object
server: at getPrototypeOf (<anonymous>)
server: at hoistNonReactStatics (/Users/apple/Desktop/dev/bethabit/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js:71:38)
server: at resolveComponent (/Users/apple/Desktop/dev/bethabit/node_modules/#loadable/component/dist/loadable.cjs.js:332:3)
server: at InnerLoadable.loadSync (/Users/apple/Desktop/dev/bethabit/node_modules/#loadable/component/dist/loadable.cjs.js:189:24)
server: at new InnerLoadable (/Users/apple/Desktop/dev/bethabit/node_modules/#loadable/component/dist/loadable.cjs.js:138:17)
server: at processChild (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3048:14)
server: at resolve (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3013:5)
server: at ReactDOMServerRenderer.render (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3436:22)
server: at ReactDOMServerRenderer.read (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3395:29)
server: at renderToStaticMarkup (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3969:27)
server: at process (/Users/apple/Desktop/dev/bethabit/node_modules/#apollo/react-ssr/lib/react-ssr.cjs.js:38:16)
server: at process._tickCallback (internal/process/next_tick.js:68:7)
server: backend debug read session { id: 3 }
server: backend debug loading <= currentUser
server: backend debug loading <= currentUser
server: backend debug loading <= currentUser
server: backend debug {"data":{"currentUser":{"id":3,"username":"canercak#gmail.com","role":"user","isActive":true,"email":"canercak#gmail.com","__typename":"User"}}} <= currentUser
server: backend debug {"data":{"currentUser":{"id":3,"username":"canercak#gmail.com","role":"user","isActive":true,"email":"canercak#gmail.com","__typename":"User"}}} <= currentUser
server: backend debug {"data":{"currentUser":{"id":3,"username":"canercak#gmail.com","role":"user","isActive":true,"email":"canercak#gmail.com","profile":{"firstName":"Caner","lastName":"Çakmak","fullName":"Caner Çakmak","__typename":"UserProfile"},"auth":{"certificate":null,"facebook":{"fbId":null,"displayName":null,"__typename":"FacebookAuth"},"google":{"googleId":"104801577244556473676","displayName":"Caner Çakmak","__typename":"GoogleAuth"},"github":null,"linkedin":null,"__typename":"UserAuth"},"__typename":"User"}}} <= currentUser
server: backend debug read session {}
server: backend error TypeError: Cannot convert undefined or null to object
server: at getPrototypeOf (<anonymous>)
server: at hoistNonReactStatics (/Users/apple/Desktop/dev/bethabit/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js:71:38)
server: at resolveComponent (/Users/apple/Desktop/dev/bethabit/node_modules/#loadable/component/dist/loadable.cjs.js:332:3)
server: at InnerLoadable.loadSync (/Users/apple/Desktop/dev/bethabit/node_modules/#loadable/component/dist/loadable.cjs.js:189:24)
server: at new InnerLoadable (/Users/apple/Desktop/dev/bethabit/node_modules/#loadable/component/dist/loadable.cjs.js:138:17)
server: at processChild (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3048:14)
server: at resolve (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3013:5)
server: at ReactDOMServerRenderer.render (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3436:22)
server: at ReactDOMServerRenderer.read (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3395:29)
server: at renderToStaticMarkup (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3969:27)
server: at process (/Users/apple/Desktop/dev/bethabit/node_modules/#apollo/react-ssr/lib/react-ssr.cjs.js:38:16)
server: at process._tickCallback (internal/process/next_tick.js:68:7)
this is the code that runs. I tried removing currentuser, addhabit and many other things to just to understand where the error comes from. No results. Everything works fine if I enter the page through a link.
HabitaddView.web.jsx
const HabitAddView = ({ addHabit, t, currentUser }) => {
const renderMetaData = () => (
<Helmet
title={`${settings.app.name} - ${t('habit.title')}`}
meta={[
{
name: 'description',
content: t('habit.meta')
}
]}
/>
);
return (
<PageLayout>
{renderMetaData()}
<div className="row">
<div className="col-sm-12 padTop10">
<h2>{t(`habit.label.create_new`)}</h2>
</div>
</div>
<HabitForm onSubmit={onSubmit(addHabit)} currentUser={currentUser} />
</PageLayout>
);
};
HabitForm.web.jsx
const HabitForm = ({ values, handleSubmit, setFieldValue, submitting, t }) => {
const [habitType, sethabitType] = useState('Fitness Habits');
const [intervalText, setIntervalText] = useState(t('habit.field.interval'));
const [habitActions, sethabitActions] = useState([]);
const [habitFreqs, sethabitFreqs] = useState([]);
const [habitDurations, sethabitDurations] = useState([]);
const [habitIntervals, sethabitIntervals] = useState([]);
const [showInterval, setshowInterval] = useState(true);
const [showHabitDiv, setshowHabitDiv] = useState(false);
const [habitActionDisabled, sethabitActionDisabled] = useState(true);
let calendarComponentRef = React.createRef();
let calendarWeekends = true;
let [calendarEvents, setCalendarEvents] = useState([]);
var timeZones = moment.tz.names();
const handleHabitTypeChange = (type, value, setFieldValue) => {
setFieldValue(type, value);
resetValues();
Object.values(settings.habits.list).map(object => {
if (object.habit_type == value) {
const _habitActions = [];
Object.values(object.habit_actions).map(object2 => {
_habitActions.push(object2.title);
});
sethabitType(value);
sethabitActions(_habitActions);
setshowHabitDiv(false);
sethabitActionDisabled(false);
}
});
};
const updateIntervalText = worktype => {
if (worktype === 5) {
setIntervalText(t('habit.field.number'));
} else if (worktype === 6 || worktype === 7) {
setIntervalText(t('habit.field.proof'));
} else {
setIntervalText(t('habit.field.interval'));
}
};
const handleHabitActionChange = (type, value, setFieldValue) => {
const preparedValue = Array.isArray(value) ? value[0] : value;
setFieldValue(type, preparedValue);
const _habitFreqs = [];
const _habitDurations = [];
const _habitIntervals = [];
resetValues();
Object.values(settings.habits.list).map(object => {
if (object.habit_type == habitType) {
Object.values(object.habit_actions).map(object2 => {
if (object2.title == preparedValue) {
Object.values(object2.duration).map(object4 => {
_habitDurations.push(object4);
});
Object.values(object2.interval).map(object5 => {
_habitIntervals.push(object5);
});
sethabitFreqs(_habitFreqs);
sethabitIntervals(_habitIntervals);
sethabitDurations(_habitDurations);
setshowHabitDiv(true);
setFieldValue('timezone', moment.tz.guess());
setFieldValue('worktype', object2.worktype);
setFieldValue('description', object2.description);
setFieldValue('misc', JSON.stringify(object2.misc));
updateIntervalText(object2.worktype);
}
});
}
});
};
const handleValueChange = (type, value, setFieldValue) => {
const preparedValue = value;
setFieldValue(type, preparedValue);
let timezone = values.timezone;
let interval = values.interval;
let duration = values.duration;
if (type === 'timezone') {
timezone = value;
} else if (type === 'interval') {
interval = value;
} else if (type === 'duration') {
duration = value;
}
updateCalendarEvents(values.habit_action, timezone, interval, duration);
};
const empty = e => {
switch (e) {
case '':
case 0:
case '0':
case null:
case false:
case typeof this == 'undefined':
return true;
default:
return false;
}
};
const resetValues = () => {
values.duration = '';
values.interval = '';
values.timezone = '';
updateCalendarEvents(values.habit_action, values.timezone, values.interval, values.duration);
};
const updateCalendarEvents = (habit_action, timezone, interval, duration) => {
setCalendarEvents([]);
let events = [];
if (!empty(timezone) && !empty(interval) && !empty(duration)) {
var dur = JSON.parse(duration);
var int = JSON.parse(interval);
var times = dur.count;
var counter = 0;
for (var i = 0; i < times; i++) {
if (i % int.step === 0) {
counter += 1;
var obj = {
title: values.habit_action + ' ' + int.title,
start: moment
.tz(values.timezone)
.add(i + 1, 'days')
.format(),
allDay: true
};
let addObj = true;
if (values.worktype === 7 && i === 0) {
addObj = false;
}
if (dur.weekdays === true && (moment(obj.start).isoWeekday() === 6 || moment(obj.start).isoWeekday() === 7)) {
addObj = false;
}
if (
values.worktype === 7 &&
counter > 2 &&
counter < 10 &&
(habit_action === 'Stay Alcohol Free' || (habit_action === 'Stay Nicotine Free' && dur.count === 28))
) {
obj.start = moment
.tz(values.timezone)
.add(i + (counter - 1), 'days')
.format();
true;
}
if (addObj) {
events.push(obj);
}
}
}
if (habit_action === 'Stay Alcohol Free' && dur.count === 28) {
events.sort(function(a, b) {
return moment(b.start) - moment(a.start);
});
events.shift();
events.shift();
}
setCalendarEvents(events);
}
};
if (settings.habits.list) {
return (
<div className="row">
<div className="col-sm-5">
<div className="card">
<div className="card-body">
<Form name="habit" onSubmit={handleSubmit}>
<Field
name="habit_type"
component={RenderSelect}
type="select"
label={t('habit.field.habit_type')}
value={values.habit_type}
onChange={value => handleHabitTypeChange('habit_type', value, setFieldValue)}
cols={1}
>
<Option value={0}>--Please Select--</Option>
{Object.values(settings.habits.list).map((object, i) => {
return (
<Option key={i} value={object.habit_type}>
{object.habit_type}
</Option>
);
})}
</Field>
habitadd.jsx
class HabitAdd extends React.Component {
static propTypes = {
currentUser: PropTypes.object
};
constructor(props) {
super(props);
this.subscription = null;
this.state = { options: [] };
}
render() {
if ( this.props.currentUser) {
return <HabitAddView {...this.props} />;
} else {
return <div></div>;
}
}
}
export default compose(
graphql(ADD_HABIT, {
props: ({ ownProps: { history, navigation }, mutate }) => ({
addHabit: async (
habit_type,
habit_action,
duration,
interval,
timezone,
description,
worktype,
misc,
user_id
) => {
let habitData = await mutate({
variables: {
input: {
habit_type: habit_type,
habit_action: habit_action,
duration: duration,
interval: interval,
timezone: timezone,
description: description,
worktype: worktype,
misc: misc,
user_id: user_id
}
},
optimisticResponse: {
__typename: 'Mutation',
addHabit: {
__typename: 'Habit',
id: null,
habit_type: habit_type,
habit_action: habit_action,
duration: duration,
interval: interval,
timezone: timezone,
description: description,
worktype: worktype,
misc: misc,
user_id: user_id,
days: [],
bets: []
}
}
});
if (history) {
window.location.href = window.location.origin + '/habit/' + habitData.data.addHabit.id;
} else if (navigation) {
return navigation.push('HabitEdit', { id: habitData.data.addHabit.id });
}
}
})
}),
graphql(CURRENT_USER_QUERY, {
props({ data: { error, currentUser } }) {
if (error) throw new Error(error);
return { currentUser };
}
})
)(HabitAdd);
Thanks to Ace, I realized my mistake.
Added this code line on habitAdd render method
render() {
if ( this.props.currentUser) {
return <HabitAddView {...this.props} />;
} else {
return <div></div>;
}
}
The issue is with the currentUser. Consider initializing it. Before routing I am assuming you are setting the value for the currentUser or the currentUser is being set to a value, but on refresh, the value is reset, though the component will load, the value for currentUser isn't available hence the error.
VSCode is helpful here. Try running the node app in debug mode with --inspect option, with Pause on Exceptions option checked.
Alternatively you could look into configuring your app to have longer stack traces, or use something like longjohn [https://www.npmjs.com/package/longjohn] that aids with that.
It happened when inlineRequires are enabled in metro.config.js. Try disabling it and run the build again...
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: true,
inlineRequires: false
}
})
}
};