Caching images in react js
I am writing an app in react js using firebase as the backend service. The images names and location is stored in the realtime database and is accessed and then the file(image) is fetched from the cloud storage and displayed on the screen.
eg.
getFile(path){
firebase.database().ref('').child(path).once('value').then(snap =>{
cloudStorage.child(snap.val()).getDownloadURL().then(url =>{
this.setState({fetchedImage: url});
});
});
}
So the fetched image url is provided as a source to an image tag
<img src={this.state.fetchedImage}/>
Can I download this and save this image to the web storage so that I download the image again when my view re-renders?
Thanks, Zeeshan
See also questions close to this topic
-
Best practices: Folder structure for client and server using create-react-app
Recently I've done a few small projects with a Node backend and a React frontend using create-react-app. Although I've spent quite a bit of time researching best practices for folder structures I haven't been able to come up with a satisfying solution without having to eject the react app. I wonder if there are solutions out there that I just haven't found yet.
The folder structure I am trying to aim for looks something like this:
package.json src/ client/ app.js ... server/ index.js (node.js main file, could just as well be in server/)
This layout would allow me to run all scripts from the root folder and I can put all configurations in one package.json. For example, I would like to be able to just run
npm test
from the root folder which would then use jest to run both the client and the server tests.As far as I can tell create-react-app is hardwired to expect a
src/index.js
when usingnpm start
, which prevents me from using this folder structure - if I just move all the boilerplate generated by create-react-app into the client folder I have an uglysrc/client/src
folder which again contains it's own package.json. I guess I could split it differently, creating aclient/src
andserver/src
, but I still have separate package.json files in each directory.Would love the hear about your experiences with this, maybe I am missing the obvious solution.
-
componentDidMount is rendering continuously in React Native
My aim is to add an splash screen with progress bar in it, so i used react-native-progress as library for progress bar. And added the screen as initial route, by performing logincheck.
I am using redux, so i created a action in order to perform the progress process in the progress bar, the code for the action as follows:
export const progressBarLevel = () => { return (dispatch) => { this.progress = 0; dispatch({ type: PROGRESS, payload: 0 }); setTimeout(() => { this.indeterminate = false; setInterval(() => { this.progress += Math.random()/5; if(this.progress > 1){ this.progress = 1; } return dispatch({ type: PROGRESS, payload: this.progress }); },250) },500) } }
Then, connected this to an reducer to save the progress. And then took the piece of progress state into the splash screen and connected via props.
Now whats happening is, i have called the progress action and login check action from componentDidMount(), as both working correctly. But for some reason the progress action is running infinitely, as i have console logged the action, " return dispatch({ type: PROGRESS, payload: this.progress }); " this is getting dispatched infinitely. I couldn't find the origin of the mistake.
My componenetDidMount() :
componentWillMount() { this.props.loginCheck(() => { this.setState({ isUserAvailble: true}) }) this.props.progressBarLevel(); }
My Progressbar code:
<View style={{ alignItems: 'center' }}> <ProgressBar progress={this.props.progressed} width={200} borderColor="#fff" color="#fff"/> </View>
I couldnt understand the problem, how to stop the continuous rendering. I even tried this using componentWillMount, there also i am getting continuous action dispatch.
Please guide.
-
Why should I prefer to use hooks and not use a class-based component instead?
I am new to Hooks, I really love the way hooks give us the ability to have state in a functional component using useState(), useEffects(), useReducer() etc, I also know it's always good to use a functional component where ever possible and limit the usage of class-based components at container level to hold the state of a root or a branch in component tree, it makes sure only a few components are managing our state and its easy to manage.
My Question: Why should I prefer to use hooks and not use a class-based component instead, what is the benefit of doing so?
I was planning to refactor my existing code base by converting many of my class-based component into functional components using hooks but I want to know whether it's worth doing so? the answers I get is gonna help me take a decision.
I am sure there is a benefit of doing so but not sure why not use class-based component instead?
-
Firebase CLI database:get request always return null
I am the owner of the firebase project from which I am trying to fetch the data, e.g.,
firebase database:get /orders
. However, the request always returnsnull
. I tried to set up different roles https://console.cloud.google.com/iam-admin/iam?project=[myproject] with no luck. I have only one firebase project and it is selected as I can see infirebase list
. I can deploy functions and app from the Firebase CLI. -
Setting port number of Firebase on socketio
I am creating a react chat application using express, socketio, firebase.
URL: https://react-chat-b0e8a.firebaseapp.com/
Github: https://github.com/kaibara/React-chatAfter creating the component, we run
node chatServer.js
and confirmed that the message can be sent on localhost.However, when checking with
firebase serve
, I can not send a message. I found out that it was enough to investigate by settingprocess.env.PORT || 3000
and implemented it, but it did not solve it.How do I configure PORT to do the same behavior as the local host on the firebase server?
I set PORT with the following three files.
chatServer.js
const express = require('express') const app = express() const server = require('http').createServer(app) const portNumber = process.env.PORT || 3000 server.listen(portNumber, () => { console.log('起動しました', 'http://localhost:' + portNumber) }) app.use('/public', express.static('./public')) app.get('/',(req,res) => { res.redirect(302, '/public') }) const socketio = require('socket.io') const io = socketio.listen(server) io.on('connection',(socket) => { console.log('Acces to User:', socket.client.id) socket.on('chatMessage',(msg) => { console.log('message',msg) io.emit('chatMessage',msg) }) })
src/components/chatApp.js
import React,{Component} from 'react' import socketio from 'socket.io-client' import ChatForm from './ChatForm' const portNumber = process.env.PORT || 3005 const socket = socketio.connect('http://localhost:' + portNumber) class ChatApp extends Component { constructor(props){ super(props) this.state = { logs: [] } } componentDidMount(){ socket.on('chatMessage',(obj) => { const logs2 = this.state.logs obj.key = 'key_' + (this.state.logs.length + 1) console.log(obj) logs2.unshift(obj) this.setState({logs: logs2}) }) } render(){ const messages = this.state.logs.map(e => ( <div key={e.key}> <span>{e.name}</span> <span>: {e.message}</span> <p /> </div> )) return( <div> <h1 id='title'>Reactチャット</h1> <ChatForm /> <div id='log'>{messages}</div> </div> ) } } export default ChatApp
src/components/chatForm.js
import React,{Component} from 'react' import socketio from 'socket.io-client' import AuthContainer from '../container/AuthContainers' import firebase from '../firebase/firebase' const portNumber = process.env.PORT || 3005 const socket = socketio.connect('http://localhost:' + portNumber) class ChatForm extends Component { constructor(props){ super(props) this.state = { name: '', message: '' } } nameChanged(e){ this.setState({name: e.target.value}) } messageChanged(e){ this.setState({message: e.target.value}) } send(){ socket.emit('chatMessage',{ name: this.state.name, message: this.state.message }) this.setState({message: ''}) } render(){ return( <div id='Form'> <div className='Name'> 名前: <br /> { this.props.uid ? <input value={this.props.displayName} />: <input value={this.state.name} onChange={e => this.nameChanged(e)} /> } </div> <AuthContainer /> <br /> <div className='Message'> メッセージ: <br /> <input value={this.state.message} onChange={e => this.messageChanged(e)} /> </div> <button className='send'onClick={e => this.send()}>送信</button> </div> ) } } export default ChatForm
Please cooperate in answering.
-
How to connect to firestore with Python without Service Account Key?
I need to connect with firestore database using python, but I don't want to use Service Account Key. Can I connect using python just with ProjectId and ApiKey?
Using javascript I can do that just like that:
firebase.initializeApp({ apiKey: process.env.REACT_APP_FIREBASE_API_KEY, projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID, });
But I can't do that using Python I get this error:
self._g_credential, self._project_id = google.auth.default(scopes=_scopes) File "/home/caique/.local/lib/python2.7/site-packages/google/auth/_default.py", line 306, in default raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application.
This is my code right now:
import firebase_admin from firebase_admin import credentials, firestore, auth cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': "my-project-id", 'apiKey': "my-api-key" }) db = firestore.client()
-
config changes without redeployment
My web application has several integrations with external systems and all these integration Rest URLs are kept in a config file with in web app. My application reads this config file at start up and use the URL values while making connections to external systems. But quite often it happens that one of the external systems is down and we have to use an alternate URL. In that case, we typically will have to modify the config and redeploy the war file. Is there a way to modify config file with new value without going through a redeployment of the war file?
-
web app- Would it be possible to disable Windows+Printscreen?
I am trying to prevent users from taking screenshot in my web application written in Java.From my research,it seems highly unlikely.I did found a link below:
https://stackoverflow.com/questions/3130983/stop-user-from-using-print-scrn-printscreen-key-of-the-keyboard-for-any-we
It's able to disable the printscreen button but it doesn't disable if a user tries to use windows+printscreen.Now, I know even if I do managed to disable it, there's other third party application like snipping tools,camera,etc to take a screenshot but that's way beyond my control and I'm not looking into those.
I was just wondering is there a way to disable
Win+Printscreen
to prevent user from screenshotting?If anyone has done it before, I appreciate any sort of suggestion.
-
How do I parse a query string with a filepath as one of the variables and download a file using that filepath variable?
I'm using node.js in order to create a new server and I would like to download a file using a filepath that is in a given URL. I also would like to pass an "action" variable inside of this query string.
For example it would be like "http://hostname:port/?action=download&filepath=c:\Users\User\Desktop\filename.txt"
I would like to extract the action and filepath and use that to complete a task such as the downloading the file. I am having a problem with extracting the filepath and passing it to the program. It seems that when I used url.parse().query it removes the slashes when I print it to the console log.
http.createServer(function (req, res) { var q = url.parse(req.url, true); var filename = "." + q.pathname; fs.readFile(filename, function(err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }); }).listen(3000, "10.0.0.171");
-
Manually set storage size limit/quota in Chrome
I am receiving
QuotaExceededError
error from Dexie.js and I would like to try to reproduce this error. On my PC though available quota is huge (14 GB). Filling it manually (even using a script) does not seems like a solution for me.Is there a way to set available storage size manually for testing purposes?
Edit: If this is possible in other browsers then it is also fine.
-
How to retrieve piece of code and change it on click
I am currently working on a project similar to the
Cursomizer
one, where my colleagues are going to be able to customize a cursor and should be able to extract the code and paste it directly into the potential project. I was doing some research on this topic but I didn't find many good answers apart from some short tutorials on local and session storage. Can any of you recommend the path I should use in order to store different code and change it live as the user clicks on the option, having in mind that I have to get this code back when all the options are fulfilled. -
If a web app's CacheStorage Cache has too much content, can the app crash?
There's not much to read on
Cache
s in the spec.I'd like to know, if I am storing LARGE amounts of data in the caches, can the web application crash? Or is the runtime memory limit of the application separate from cache storage? Will the Cache unload runtime memory and fallback on filesystem if needed? Or will the Cache try to load everything into memory (thus crash)? What does it do?
I'm looking for insight into whether or not having a TON of stuff in the cache can be a source for crashes I'm experiencing.