Trying to render react components off database - node.js

Basically this is my code to render components
return (
<>
{props.Sites.map((Sites) => (
<Box maxW='sm' borderWidth='1px' borderRadius='lg' overflow='hidden'>
<Image src={Sites.imageUrl} alt={Sites.imageAlt} onClick={() => console.log(Sites.title)} />
<Box p='6'>
<Box display='flex' alignItems='baseline'>
<Box
color='gray.500'
fontWeight='semibold'
letterSpacing='wide'
fontSize='xs'
textTransform='uppercase'
ml='2'
>
Inverters {Sites.Inverters} • Size {Sites.PvSize} kW
</Box>
</Box>
<Box
mt='1'
fontWeight='semibold'
as='h4'
lineHeight='tight'
isTruncated
>
{Sites.title}
</Box>
</Box>
</Box>
))}
</>
)
}
i parse the object from props that the function then uses to render components.
what I'm trying to do is have those objects come from a database such as mongogdb. ive been trying to use mongoose with express server but nothing seems to be working. right now the objects are just written up before the function renders and id rather it come form an actual db.
i would like to know the proper approach to his kind of thing and where to go form here thanks.

Related

Re-fetching data automatically when Database values changes

Inside my react App, i have a component that shows a list of data fetched from my database.
Now i would like to refresh my component every "X" seconds so if the database values have changed, my component will show also those new values.
Here's my code...
const SingleBet = () => {
const { data } = useGetAllBetsQuery() //REDUX FETCH
return (
<Paper sx={{marginTop:"10px", background:"white"}}>
<Grid container xs={12} sx={{display:"flex", flexDirection:"row", height:"50px"}}>
//ITEMS NO NEEDED
</Grid>
{data.map((data, index) => {
return (
<Paper sx={sxPaperList} key={index}>
<Grid container rowSpacing={2} sx={sxGridContainer}>
<Grid item xs={4} >
{data.ImportoG1 > 0 ? (
<Typography variant="h6" sx={sxTypographyNames}>{data.Giocatore1}
<img src={star} alt="little_star" height="15"/></Typography>
) : (
<Typography variant="h6" sx={sxTypographyNames}>
{data.Giocatore1}
</Typography>
)}
//OTHER THINGS LIKE THIS
</Grid>
</Paper>
)
})}
</Paper>
)
}
How u can see i fetch data from my DATABASE using redux. Now i would like to refresh this component every 5 seconds so that if DATABASE changes, every 5 seconds my component refreshes and show new values
I tried playing with useEffect but i couldnt reach to get any good results. Please help me :D
Here's my useGetAllBetsQuery() code
export const liveApi = createApi({
reducerPath: "liveApi",
baseQuery: fetchBaseQuery({baseUrl: URL}),
endpoints: (builder) => ({
getAllBets: builder.query({
query: () => "live",
})
})
})
export const { useGetAllBetsQuery } = liveApi

How to get props from another component in styled-components

I'm trying to pass props to a child component's styled components so that I can dynamically set CSS styling. The below is what I tried, but it always goes false which is 50%. Seems like the props do not get passed down.
components/Col.js
const Col = styled.div`
flex: ${props => (props.size < 6 ? "0 0 100%" : "0 0 50%")};
max-width: ${props => (props.size < 6 ? "100%" : "50%")};
`;
export default ({ children }) => <Col>{children}</Col>;
pages/index.js
export default () => (
<App>
<Header />
<Row>
<Col size={3}>
<Card />
</Col>
</Row>
</App>
);
I put your code in a codesandbox and it functions as expected, there are 2 <Col />s, one which has a size of less than 6 and one greater, and the correct CSS rules are being applied based on props.
https://codesandbox.io/s/epicpoincaresd6ig-sd6ig
Are you sure it's not something in the <Card />'s CSS? Maybe you can post a sandbox link demonstrating your issue.

require() not displaying for local images React Native

I'm using React Native 0.54.0-rc.3, and that means that I'm of a recent enough version to load local static images using the require=() statement.
I've tried doing it for my react-native app, but the images are not showing, and I'm not sure why.
Most if the issues I found online were not helpful, as they were either new to the concept of the require statement or they had syntax errors.
There other errors seemed unrelated to me.
Here's an exact look at my code:
<Image resizeMethod = "resize" source={require('../../images/ssnit_logo_high_def.png')} style = {{width: 200, height: 200}} />
<Text style = {styles.title}> About SSNIT </Text>
<Button title = 'Visit our Website' onPress = {() => this.goToURL("https://www.ssnit.org.gh", "Your device doesn't support internet browsing")}/>
<View style= {[styles.container,{flexDirection: 'row', height: 60}]} >
<SocialIcon style = {{margin: 5}}
light
type='envelope'
onPress = {() => this.goToURL('mailto:contactcentre#ssnit.org.gh', "Your device doesn't seem to support email")}
/>
<SocialIcon
light
type='facebook'
onPress = {() => this.goToURL('https://www.facebook.com/ssnitghana', "Your device doesn't seem to support internet browsing")}
/>
<SocialIcon
light
type='twitter'
onPress = {() => this.goToURL('https://twitter.com/ssnitghana?lang=en', "Your device doesn't seem to support internert browning")}
/>
</View>
<Text style = {styles.paragraph}> Contact Credientials </Text>
<View style= {[styles.container,{flexDirection: 'row', height: 50}]}>
<Text style = {styles.subtext}> +233 302 611 622 </Text>
<Button title = 'Call this number' onPress = {() => this.goToURL("tel:+233302611622", "Your device doesn't support phone calls")}/>
</View>
<View style= {[styles.container,{flexDirection: 'row', height: 50}]}>
<Text style = {styles.subtext}> +233 800 1100 94 </Text>
<Button title = 'Call this number' onPress = {() => this.goToURL("tel:+233800110094", "Your device doesn't support phone calls")}/>
</View>
<Text style = {styles.subtext}> contactcentre#ssnit.org.gh </Text>
<Text style = {styles.paragraph}> More About Us </Text>
{this.state.pages.map(info =>
<TouchableOpacity key = {info.pageName} style ={styles.informationCells} onPress = {() => this.props.navigation.navigate(info.pageName)}>
<Text style = {[styles.paragraph, {color: "#007AFF", fontWeight: "bold"}]}> {info.title} </Text>
<Image source={require("../../images/navigation_arrow.png")} style = {{width: 100, height: 100}} resizeMode="contain" />
</TouchableOpacity>
)}
</ScrollView>
React Native can definitely knows that such a file exists (since entering a non-existent path leads to an error), and space has been made for the image, but it's simple blank. This is the issue for both image components.
Has anyone else had an issue like this? Some help would be appreciated.
So, I managed to find a workaround. It turns out that the images will show on the emulator if you bundle the app through the terminal before launching it on the emulator. Strangely, bundling also happened to be the solution to a problem that prevented me from running the app on a real Android device, so the problems might be related.
Anyway, to learn how to bundle, look at this StackOverflow answer. Info can also be found on this GitHub issue.
I had an issue like this, The require() method was actually returning an object with the source for the picture inside of the default value.
If it is the same problem, you can try this:
<Image
resizeMethod="resize"
source={require('../../images/ssnit_logo_high_def.png').default}
style={{width: 200, height: 200}}
/>

TouchableHighLight onPress inside a map function in react native

I have an array of images that I want to display in a component in react native.
I use map function to iterate over the array and display it. I also have a delete button on top of the image.
The relevant code is :
this.state.imgs.map(function(img,i){
return (
<View style={{alignItems:'center',justifyContent:'center', height:75, width:75, borderRadius:25}}>
<Image style={{position:'absolute',resizeMode:'cover', top:0,left:0, borderRadius:38,height:75, width:75, opacity:0.5}} source={{uri: img.path }} />
<TouchableHighlight onPress={() => this.removeItem(i)}>
<Image style={{}} source={require('./Images/images_asset65.png')} />
</TouchableHighlight>
</View>
);
})
The problem is the TouchableHighlight, where I have an event, when the event fires I get an error regarding "this" (undefined is not a function).
I know this is a scope problem but I cant figure it out.
Is the use of an arrow function is correct here?
If you want to use this inside your map function, you have to change to an arrow function so this points to the outer scope.
this.state.imgs.map((img, i) => {
return (
<View style={{alignItems:'center',justifyContent:'center', height:75, width:75, borderRadius:25}}>
<Image style={{position:'absolute',resizeMode:'cover', top:0,left:0, borderRadius:38,height:75, width:75, opacity:0.5}} source={{uri: img.path }} />
<TouchableHighlight onPress={() => this.removeItem(i)}>
<Image style={{}} source={require('./Images/images_asset65.png')} />
</TouchableHighlight>
</View>
);
})
When you use function keyword in your code, then you lose the context and function creates its own. If you use function it is better not to forget binding these functions with bind(this) so that these functions share the same context. So in your relevant code you should change your last line to }.bind(this)). It is better to remember using bind(this) somehow when using the function keyword, even the better option is not using function and stick with the goodies comes with ES6. Last but not least one should always read docs.

What does GET /bla - - ms - - mean in NodeJs console?

When I go to the page /bla in my NodeJS app, the console prints out
GET /bla - - ms - -
In words (for easier Google searches), dash dash ms dash dash.
What does this mean?
This is the output from morgan, a HTTP request logger middleware for node.js.
It logs all requests, by default, to the console. Depending on your configurations it will display different data from the request.
If you are using the default format (dev), the data displayed is:
:method :url :status :response-time ms - :res[content-length]
According to this thread:
The log line GET / - - ms - - is the dev format saying you never sent a response before Node.js killed the TCP connection for idling too long.
So the problem is a request that wasn't responded by the server - in other words, some middleware along the route never called next(), res.send(), res.end() or any other means to respond.
I realized that this can also occur if the server doesn't handle the client aborting the request (can be easily tested by e.g making the request through a browser and clicking on the X button in the address bar before it's done).
According to the docs, the way to handle that would probably be something like (wasn't tested):
req.on('abort', function (err) {
if (err)
console.error(error.message);
// your code here
});
Maybe its a front issue, try postman see if you have the same issue
I had the same issue , but I observed that if I use my POSTMAN, the issue never pops up, but my react app at times returns correct request but most other times there was no response and POST /story/create - - ms - - was the express log. When I looked at the code, the form submission was very weird in the front rend
<Form onSubmit={() => formTest()}>
<div
style={{ display: "flex", justifyContent: "center" }}
key={`inline-switch`}
className="mb-3"
>
{checkboxes.map((name, index) => (
<div key={index.toString()} className="mb-3">
<Form.Check
onChange={() => handleOnChange(index)}
label={name}
name="group1"
type="switch"
id={`inline-switch-${index}`}
/>
</div>
))}
</div>
<div style={{ display: "grid", placeItems: "center" }}>
<BootstrapButton
style={{ backgroundColor: "Blue", width: "48%" }}
type="submit"
>
Submit
</BootstrapButton>
and when I cleaned it up
<Form >
<div
style={{ display: "flex", justifyContent: "center" }}
key={`inline-switch`}
className="mb-3"
>
{checkboxes.map((name, index) => (
<div key={index.toString()} className="mb-3">
<Form.Check
onChange={() => handleOnChange(index)}
label={name}
name="group1"
type="switch"
id={`inline-switch-${index}`}
/>
</div>
))}
</div>
<div style={{ display: "grid", placeItems: "center" }}>
<BootstrapButton
style={{ backgroundColor: "Blue", width: "48%" }}
onClick= {() => formTest()}
>
Submit
</BootstrapButton>
The error no longer popped up. I don't know the reason nor I guarantee that this the real issue, but I suggest try to recreate by using CURL or postman or even other code like other react component's fetches. Maybe you can fix the issue

Resources