Attempting to create a custom booking widget component, on this file i'm doing an asynchronous API call but got uncaught in promise error cannot read property lenght of undefined.... This is a JSX file and I'm using a simple boilerplate...using an example of binary search to iterate between response data which returns two objects.need to get the value of an id and a json file included locally has the styles for the primarycolor,contrastcolor,hovercolor,banner,and logo respectively
import React, {useEffect, useState } from 'react';
import Form from '../components/Form';
import styles from '../Styles/style.css';
import getStyleFromDb from '../api/themes';
import axios from 'axios';
const App = () => {
const [loading, setLoading] = useState(true);
const [primary_color, set_primary_color] = useState('#fff');
const [contrast_color, set_contrast_color] = useState('#ccc');
const [hover_color, set_hover_color] = useState('#000000');
const [banner, setBanner] = useState([]);
const [logo, setLogo] = useState('');
useEffect(() => {
async function fetchData() {
const config = {
method: 'get',
url: '/src/api/customThemes.json'
}
let res = await axios(config);
function objectSearch(filter, clients) {
let found = false;
let position = -1;
let index = 0;
while(!found && index > clients.length) {
if(list[index] == filter) {
found = true;
position = index;
} else {
index += 1;
}
}
return position;
}
let settings = objectSearch(filter, clients);
console.log('id response', res.data);
let clients = res.data;
let filter = clients.find((clients => clients.id) === '12345');
settings = filter;
set_primary_color(settings.primary_color);
set_contrast_color(settings.contrast_color);
set_hover_color(settings.hover_color);
setLogo(settings.logo);
setBanner(settings.banner);
setLoading(false);
}
fetchData();
}, []);
if(loading) return 'loading';
return(
<div className={styles.container} >
<img src="/src/assets/img/beach-background.jpg" className={styles.background} alt="Booking-Widget-Background" />
<h1 className={styles.title}>
Booking Widget
</h1>
<Form primary_color={primary_color} contrast_color={contrast_color} hover_color={hover_color} />
</div>
);
};
export default App;
You are trying to use filter and clients here:
let settings = objectSearch(filter, clients);
before they are even declared (so they will be undefied). You need to put this line after:
let filter = clients.find((clients => clients.id) === '12345');
You should look into linting (ESLint) or TypeScript. They can warn you in compile time about these kind of errors. It really simplifies development.
Hope this helps.