Couldn't load resource Error : net::ERR_CONNECTION_REFUSED - reactjs

i'm using react JS for front end and .NET API for backend , i'm trying to fetch data from API , i enabled CORS (i added some configuration in startup file ) and it's all fine normally .
in react js , i want to fetch data using my API so this is my code to show a list of data :
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { List, Avatar, Button, Spin } from "antd";
import PropTypes from "prop-types";
import { withStyles } from "#material-ui/core/styles";
import reqwest from "reqwest";
const fakeDataUrl =
"http://localhost:51492/api/experience/";
class LoadMoreList extends React.Component {
state = {
loading: true,
loadingMore: false,
showLoadingMore: true,
data: []
};
componentDidMount() {
this.getData(res => {
this.setState({
loading: false,
data: res.results
});
});
}
getData = callback => {
reqwest({
url: fakeDataUrl,
type: "json",
method: "get",
contentType: "application/json",
success: res => {
callback(res);
}
});
};
onLoadMore = () => {
this.setState({
loadingMore: true
});
this.getData(res => {
const data = this.state.data.concat(res.results);
this.setState(
{
data,
loadingMore: false
},
() => {
// Resetting window's offsetTop so as to display react-virtualized demo underfloor.
// In real scene, you can using public method of react-virtualized:
// https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
window.dispatchEvent(new Event("resize"));
}
);
});
};
render() {
const { loading, loadingMore, showLoadingMore, data } = this.state;
const loadMore = showLoadingMore ? (
<div
style={{
textAlign: "center",
marginTop: 12,
height: 32,
lineHeight: "32px"
}}
>
{loadingMore && <Spin />}
{!loadingMore && (
<Button onClick={this.onLoadMore}>loading more</Button>
)}
</div>
) : null;
return (
<List
style={{
width: "50%",
left: "25%"
}}
className="demo-loadmore-list"
loading={loading}
itemLayout="horizontal"
loadMore={loadMore}
dataSource={data}
renderItem={item => (
<List.Item
actions={[
<Button type="primary" icon="user-add">
suivre
</Button>,
<a>Message</a>
]}
>
<List.Item.Meta
avatar={
<a>
<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />{" "}
</a>
}
title={{item.titre}}
/>
</List.Item>
)}
/>
);
}
}
LoadMoreList.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles()(LoadMoreList);
this code will show a list of experiences and it allows us to load more data clicking on LoadMore
but what i get when i start the project :
and in DevTools i get this error
Failed to load resource: net::ERR_CONNECTION_REFUSED
i looked in google for many solutions but no one helped me
thanks for helping me .

Related

How to test get/post(which takes param) API which is created inside Context and called in other component?

I have created a function which fetches data from API and send a response of userDetail, which has been created in context. and function has been called in Dashboard component by importing context. And when user clicks button it render userData.
I am tried testing to check function has been called once or not, after click. but not able to achieve it.
Context Page
here userDataFunc is created .
import React, { Component, createContext } from "react";
import axios from "axios";
export const Contx = createContext();
export class ConProvider extends Component {
state = {
userData: []
};
userDataFunc = async () => {
await axios(`https://jsonplaceholder.typicode.com/users`)
.then((res) => {
if (res.status === 200) {
this.setState({
userData: res.data
});
}
})
.catch((err) =>
this.setState({
userDataerror: err
})
);
};
render() {
console.log(this.state.coin);
return (
<Contx.Provider
value={{
...this.state,
userDataFunc: this.userDataFunc
}}
>
{this.props.children}
</Contx.Provider>
);
}
}
Dashboard Component
Here Function and userdata state has been imported from context
import React, { useContext } from "react";
import { Contx } from "../ContextApi";
export default function Dashboard() {
const { userDataFunc, userData } = useContext(Contx);
return (
<div
style={{ height: "100vh", backgroundColor: "#151515" }}
className="d-flex justify-content-center align-items-center"
>
<button data-testid="renderData" onClick={userDataFunc}>
Render Data
</button>
<div
style={{
overflowY: "auto",
margin: "4px",
border: "2px solid",
padding: "12px",
height: "80vh"
}}
data-testid="tableData"
>
{userData.map((i) => {
return (
<h5 key={i.id} style={{ color: "#fff" }}>
{i.name}
</h5>
);
})}
</div>
</div>
);
}
Dashboard Test File
// import React from "react";
import { fireEvent, render } from "#testing-library/react";
import axiosMock from "axios";
import Dashboard from "./Dashboard";
import { Contx } from "../ContextApi";
jest.mock("axios");
it("Api Called", () => {
const { getByTestId } = render(
<Contx>
<Dashboard />
</Contx>
);
const renderButton = getByTestId("userData");
fireEvent.click(renderButton);
expect(Dashboard.userDataFunc()).toHaveBeenCalledTimes(1);
});

react hooks not setting the select value after fetching options

I am fetching list of testsuites using api call on component mount. Api returns list in chronological order.
Setting them as options for a select dropdown(Material-UI).
Then set the selected option to latest testSuite and using its Id get the corresponding testSuite data.
Data is retrieved successfully and pie chart is getting displayed.
Api calls are working fine and React dev tools shows the selectedTestSuite value to be set correctly.But DOM doesn't show the selection in the select dropdown.
Can someone please advise what is the mistake I am doing in this code? Thanks in advance.
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { Doughnut } from 'react-chartjs-2';
import { makeStyles } from '#material-ui/styles';
import axios from 'axios';
import { useSpring, animated } from 'react-spring';
import '../../Dashboard.css';
import MenuItem from '#material-ui/core/MenuItem';
import {
Card,
CardHeader,
CardContent,
Divider,
TextField,
} from '#material-ui/core';
import CircularProgress from '#material-ui/core/CircularProgress';
const useStyles = makeStyles(() => ({
circularloader: {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
},
actions: {
justifyContent: 'flex-end',
},
inputField: {
width: '150px',
},
}));
const TestSuiteVsScanCount = (props) => {
const { className, ...rest } = props;
const classes = useStyles();
const [doughData, setDoughData] = useState([]);
const [dataLoadedFlag, setDataLoadedFlag] = useState(false);
const [testSuites, setTestSuites] = useState([]);
const [selectedTestSuite, setSelectedTestSuite] = useState({});
useEffect(() => {
function getTestSuites() {
axios.get('http://localhost:3000/api/v1/testsuite/12').then((resp) => {
setTestSuites(resp.data.reverse());
});
}
getTestSuites();
}, []);
useEffect(() => {
if (testSuites.length > 0) {
setSelectedTestSuite(() => {
return {
type: testSuites[0].TestSuiteName,
id: testSuites[0].TestSuiteId,
};
});
}
}, [testSuites]);
useEffect(() => {
function getTestSuiteData() {
let doughData = [];
if (selectedTestSuite.id) {
axios
.get(
'http://localhost:3000/api/v1/summary/piechart/12?days=30&testsuiteid=' +
selectedTestSuite.id,
)
.then((resp) => {
resp.data.forEach((test) => {
doughData = [test.TestCount, test.ScanCount];
});
setDoughData({
labels: ['Test Count', 'Scan Count'],
datasets: [
{
data: doughData,
backgroundColor: ['#FF6384', '#36A2EB'],
hoverBackgroundColor: ['#FF6384', '#36A2EB'],
},
],
});
setDataLoadedFlag(true);
});
}
}
getTestSuiteData();
}, [selectedTestSuite]);
const ChangeType = (id) => {
testSuites.forEach((suite) => {
if (suite.TestSuiteId === id) {
setSelectedTestSuite({
type: suite.TestSuiteName,
id: suite.TestSuiteId,
});
}
});
};
return (
<Card {...rest} className={clsx(classes.root, className)}>
<CardHeader
action={
<TextField
select
label="Select Test Suite"
placeholder="Select Tests"
value={selectedTestSuite.id}
className={classes.inputField}
name="tests"
onChange={(event) => ChangeType(event.target.value)}
variant="outlined"
InputLabelProps={{
shrink: true,
}}
>
{testSuites.map((testSuite) => (
<MenuItem
key={testSuite.TestSuiteId}
value={testSuite.TestSuiteId}
>
{testSuite.TestSuiteName}
</MenuItem>
))}
</TextField>
}
title="Test Suite vs Scan Count"
/>
<Divider />
<CardContent>
<div>
{dataLoadedFlag ? (
<Doughnut data={doughData} />
) : (
<CircularProgress
thickness="1.0"
size={100}
className={classes.circularloader}
/>
)}
</div>
</CardContent>
<Divider />
</Card>
);
};
TestSuiteVsScanCount.propTypes = {
className: PropTypes.string,
};
export default TestSuiteVsScanCount;
I was able to fix this issue with the help of my colleague by setting the initial state of selectedTestSuite to {type:'', id:0} instead of {}.
Changed this
const [selectedTestSuite, setSelectedTestSuite] = useState({});
To this
const [selectedTestSuite, setSelectedTestSuite] = useState({type:'', id:0});
But I am not sure why this worked.
I believe that the main problem is when you pass a value to TextField component with undefined, the TextField component will assume that is an uncontrolled component.
When you set you initial state for selectedTestSuite to be {} the value for selectedTestSuite.id will be undefined. You can find value API reference in https://material-ui.com/api/text-field/

ReactJS - onClick SweetAlert is not working

I'm using ReactJS (and nodejs, mongodb..) and I have projects with the delete option and I want to show a delete alert confirm window and I'm using SweetAlert for the first time. It shows the SweetAlert but doesn't let me choose the option, delete the project immediately. I'll show a gif so you can see what is happening.
Thank you!
My ProjectPage Component:
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import moment from 'moment';
import SweetAlert from 'react-bootstrap-sweetalert'
import Tasks from '../../TaskList/Tasks/Tasks';
import './ProjectPage.css';
class ProjectPage extends Component {
constructor(props) {
super(props);
this.state = {
project: {},
alert: null
};
}
componentDidMount() {
const { match: { params } } = this.props;
fetch(`/dashboard/project/${params.id}`)
.then(response => {
return response.json()
}).then(project => {
this.setState({
project: project
})
})
}
deleteProject(e){
const getAlert = () => (
<SweetAlert
warning
showCancel
confirmBtnText="Yes!"
confirmBtnBsStyle="danger"
cancelBtnBsStyle="default"
title="Are you sure you want to delete this project?"
onConfirm={() => this.deleteFile()}
onCancel={() => this.onCancelDelete()}
>
You will not be able to recover this project!
</SweetAlert>
);
this.setState({
alert: getAlert()
});
e.preventDefault();
}
onCancelDelete(){
this.setState({
alert: null
});
}
render() {
const { match: { params } } = this.props;
const BackgroundImage = {
backgroundImage: `url(${this.state.project.imageURL})`,
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
backgroundPosition: 'center',
height: '350px',
opacity: '0.7'
}
return (
<div>
<header style={BackgroundImage}>
[...]
<form method='POST' action={`/dashboard/project/${params.id}/delete?_method=DELETE`}>
<button id='button__project-delete' style={{ boxShadow: 'none' }} className='button__options--project btn btn-outline-secondary'
type='submit' onClick={() => this.deleteProject()}>Delete</button> {this.state.alert}
</form>
</header>
[...]
</div>
);
}
}
export default ProjectPage;
GIF what's happening:
It looks your page refreshed on button click, because it is inside a form object. On button click, click event can not be accessible. So e.preventDefault() does not work.
You have to pass event object to deleteProject() method.
Change this line
<button id='button__project-delete' style={{ boxShadow: 'none' }} className='button__options--project btn btn-outline-secondary'
type='submit' onClick={() => this.deleteProject()}>Delete</button> {this.state.alert}
to
<button id='button__project-delete' style={{ boxShadow: 'none' }} className='button__options--project btn btn-outline-secondary'
type='submit' onClick={(e) => this.deleteProject(e)}>Delete</button> {this.state.alert}
this.setState({
alert: getAlert()
});
Please check after changing this to
this.setState({
alert: getAlert
});

fetching data from api in React Js failed

i'm new in react js and i'm trying to fetch data from My API , which i can its result with POSTMAN , and it shows the data
My problem is when i use the link :" http://localhost:51492/api/user/1 " in my react js app , data couldn't appear ...
PS : je travail avec Code SandBox
here is my code showing all the followers of a user :
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { List, Avatar, Button, Spin } from "antd";
import PropTypes from "prop-types";
import { withStyles } from "#material-ui/core/styles";
import reqwest from "reqwest";
const fakeDataUrl =
"http://localhost:51492/api/follower/all/1";
class LoadMoreList extends React.Component {
state = {
loading: true,
loadingMore: false,
showLoadingMore: true,
data: []
};
componentDidMount() {
this.getData(res => {
this.setState({
loading: false,
data: res.results
});
});
}
getData = callback => {
reqwest({
url: fakeDataUrl,
type: "json",
method: "get",
contentType: "application/json",
success: res => {
callback(res);
}
});
};
onLoadMore = () => {
this.setState({
loadingMore: true
});
this.getData(res => {
const data = this.state.data.concat(res.results);
this.setState(
{
data,
loadingMore: false
},
() => {
// Resetting window's offsetTop so as to display react-virtualized demo underfloor.
// In real scene, you can using public method of react-virtualized:
// https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
window.dispatchEvent(new Event("resize"));
}
);
});
};
render() {
const { loading, loadingMore, showLoadingMore, data } = this.state;
const loadMore = showLoadingMore ? (
<div
style={{
textAlign: "center",
marginTop: 12,
height: 32,
lineHeight: "32px"
}}
>
{loadingMore && <Spin />}
{!loadingMore && (
<Button onClick={this.onLoadMore}>loading more</Button>
)}
</div>
) : null;
return (
<List
style={{
width: "50%",
left: "25%"
}}
className="demo-loadmore-list"
loading={loading}
itemLayout="horizontal"
loadMore={loadMore}
dataSource={data}
renderItem={item => (
<List.Item
actions={[
<Button type="primary" icon="user-add">
suivre
</Button>,
<a>Message</a>
]}
>
<List.Item.Meta
avatar={
<a>
<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />{" "}
</a>
}
title={{item.userProfile}}
/>
</List.Item>
)}
/>
);
}
}
LoadMoreList.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles()(LoadMoreList);
and here is what PostMan shows when i enter the URL : http://localhost:51492/api/follower/all/1
what i thinks is missing is the "results attribute" at the beginning of the result in postman , i think it must be like that :
please help me , and thank u for ur interest

how to set center on StandaloneSearchBox in react google maps

i'm using react google maps standalonesearchbox,every thing is ok,but how can i show first near by location in google map search hints(places),generally when we use map with search box then we attach both each other but here i didn't add map.
so here my question is how can i set center or show nearby search first on google places search hints.
here is my code
import React from 'react';
import {connect} from 'react-redux';
import { Input,Icon} from 'antd';
import 'antd/dist/antd.css';
import {pickupHandler,pickupAddHandler,dropoffHandler} from '../actions';
import config from '../../../config'
const { compose, withProps, lifecycle,withHandlers } = require("recompose");
const {
withScriptjs,
} = require("react-google-maps");
const { StandaloneSearchBox } = require("react-google-maps/lib/components/places/StandaloneSearchBox");
const SearchBox = compose(
withProps({
googleMapURL: config.MapApi,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
}),
lifecycle({
componentWillMount() {
const refs = {}
this.setState({
onSearchBoxMounted: ref => {
refs.searchBox = ref;
},
onBoundsChanged: () => {
this.setState({
bounds: refs.map.getBounds(),
center: refs.map.getCenter(),
})
},
onPlacesChanged: () => {
const places = refs.searchBox.getPlaces();
places.map(({ place_id, formatted_address, geometry: { location } }) =>{
this.props.latlngHandler({lat:location.lat(),lng:location.lng()})
this.props.AddressHandler(formatted_address)
})
this.setState({
places,
});
},
suffix: () =>{
this.props.AddressHandler('')
this.props.latlngHandler(false);
}
})
},
}),
withHandlers(() => {
return{
cutPickIcon:<Icon type="close-circle" />
}
}),
withScriptjs
)(props =>
<div data-standalone-searchbox="">
<StandaloneSearchBox
ref={props.onSearchBoxMounted}
bounds={props.bounds}
onBoundsChanged={props.onBoundsChanged}
onPlacesChanged={props.onPlacesChanged}
>
<Input
prefix={<Icon type="environment-o" style={props.name === 'pick' ? { color: '#EA4335' }: { color: '#00E64D' }} />}
type="text"
placeholder={props.placeHoler}
onChange={props.Field}
onFocus={props.FocusGA}
value={props.Address}
className='input'
suffix={props.Suffix ? <Icon type="close-circle" onClick={props.suffix}/> :''}
/>
</StandaloneSearchBox>
</div>
);
export default connect(null,{pickupAddHandler,pickupHandler,dropoffHandler})(SearchBox)
You can use the maps geocode to set bounds prop on StandaloneSearchBox.
Please refer to my answer on this post.
https://stackoverflow.com/a/53396781/1661712

Resources