environment:react 17.x、umi 3.5.21
In this code below, I send a request and build an array of components, using console.log(hosCardArr) in then has content
let hosCardArr: any[] = [];
useEffect(() => {
getHosList({ _location: location, _level: level }).then(function (
response: returnHosInfo[],
) {
let arr: any[] = [];
for (let i = 0; i < response.length; i++) {
let e: returnHosInfo = response[i]
if (i % 2 == 0) {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='left' />)
} else {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='right' />)
}
}
hosCardArr = arr
});
});
In this code below, I render the array, using console.log(hosCardArr) in <div><div/> the result is []
<div>{hosCardArr}</div>
The end result is that the elements in the array are not displayed
The focus of this question is on data flow,If I don't use state, it will render the array empty and not updated
const [hosCardArr, setHosCardArr] = useState<any[]>([]);
useEffect(() => {
getHosList({ _location: location, _level: level }).then(function (
response: returnHosInfo[],
) {
let arr: any[] = [];
for (let i = 0; i < response.length; i++) {
let e: returnHosInfo = response[i]
if (i % 2 == 0) {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='left' />)
} else {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='right' />)
}
}
setHosCardArr(arr)
});
}, []);
you must use .map function to render each item of the array , like this :
return (
<>
{
hosCardArr.map((hos,index) =>
<div key={index}>{hos}</div>
);
}
</>
)
Related
I'm using this react-beautiful-dnd library to be able to reorder lists. However, even though I'm able to drag and drop and re-order, there is a flicker when I try to move a card from one list to another list I call API when a card is dragged to the destination list
const onDragEnd = (result: any) => {
if (!result.destination) {
return;
}
const listCopy: any = { ...elements };
const sourceList = listCopy[result.source.droppableId];
const [removedElement, newSourceList] = removeFromList(
sourceList,
result.source.index
);
listCopy[result.source.droppableId] = newSourceList;
const destinationList = listCopy[result.destination.droppableId];
listCopy[result.destination.droppableId] = addToList(
result.destination.droppableId,
destinationList || [],
result.destination.index,
removedElement,
result.source.droppableId
);
setElements(listCopy)};
and in addToList function I am calling API to update order on server
const addToList = (
changedList: string,
list: any[],
index: number,
element: any,
currentListId: string
) => {
let cardOrder;
const result = Array.from(list);
result.splice(index, 0, element);
const cardCurrentIndex = result.findIndex((item) => item.id === element.id);
if (list.length === 0) {
cardOrder = DEFAULT_PIPELINE_ORDER;
} else if (cardCurrentIndex === 0 && result.length !== 0) {
const nextCardOrder = result[1];
cardOrder = nextCardOrder.current_stage_order - STAGE_INCREMENT_AMOUNT;
} else if (cardCurrentIndex === result.length - 1) {
const nextCardOrder = result[result.length - 2];
cardOrder = nextCardOrder.current_stage_order + STAGE_INCREMENT_AMOUNT;
} else if (
Boolean(result[cardCurrentIndex - 1]) &&
Boolean(result[cardCurrentIndex + 1])
) {
cardOrder = Math.round(
(result[cardCurrentIndex - 1].current_stage_order +
result[cardCurrentIndex + 1].current_stage_order) /
2
);
}
let candidatesData: any = elements;
if (candidatesData) {
if (currentListId === changedList) {
candidatesData[changedList as any] = result as unknown as elementsType;
setElements([...candidatesData]);
} else {
candidatesData[currentListId as any] = candidatesData[
currentListId as any
]?.filter((item: any) => item.id !== element.id);
candidatesData[changedList as any] = result as unknown as elementsType;
setElements([...candidatesData]);
console.log("[...candidatesData]", [...candidatesData]);
}
}
const stageId = stagePipeLineLanes?.find(
(item) => item.id.toString() === changedList.toLowerCase()
)?.id;
if (
changedList === "applied" ||
changedList === "sourcing" ||
changedList === "interviewing"
) {
const changedDestination = changedList;
const destinationStages = positionDetails?.candidate_stages.filter(
(item) =>
item.pipeline.toLowerCase() === changedDestination.toLowerCase()
);
const stage = destinationStages.find((item) => item.is_default === true);
mutate(
{
candidateId: element.id.toString(),
data: compressObject({
stage: stage?.id.toString(),
}),
},
{
onSuccess: (response) => {
if (response) {
toast.success(
`Candidate moved to ${capitalizeFirstLetter(
changedDestination
)}`
);
}
},
}
);
} else {
mutate({
candidateId: element.id.toString(),
data: compressObject({
stage: stageId?.toString() || "",
current_stage_order: cardOrder?.toString() || "",
}),
});
}
return result;
};
I have been trying to mock my localeStorage with that library https://www.npmjs.com/package/jest-localstorage-mock
But it always shows me the next mistake
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
Here is mine test
it('checks the locale cost element', () => {
const headerCoinCost = 544123.123543;
const KEY = "walletData",
VALUE = '[{"id":"bitcoin","name":"Bitcoin","price":"38953.6908005677844877","amount":"1"}]';
render(<HeaderWallet headerCoinCost={headerCoinCost} onClick={true ? true : false} ></HeaderWallet>);
const userWalletDifferenceElement = screen.getByTestId("user-wallet__different-cost-test");
expect(userWalletDifferenceElement).toBeInTheDocument();
dispatch(action.update(KEY, VALUE));
expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
expect(localStorage.__STORE__[KEY]).toBe(VALUE);
expect(Object.keys(localStorage.__STORE__).length).toBe(1);
expect(userWalletDifferenceElement).toHaveTextContent(544123.12);
});
component where I get mistake
export const getLocaleCost = () => {
let localCostArr = [];
let sum = 0;
let existingEntries = JSON.parse(localStorage.getItem("walletData"));
if (existingEntries == null) existingEntries = [];
existingEntries.map(el => {
localCostArr.push(el.price * el.amount)
});
for (let i = 0; i < localCostArr.length; i++) {
sum += +localCostArr[i];
};
return sum;
};
anybody know why the data exists in line 267 but not in 268? Any help is appreciated , thank you.
code
console
full function with useEffect watching props value to trigger the function
function createData() {
//loop through employees and create obj array
const emptyArray = [];
let counter = 0;
if (props.employees) {
const rowData = props.employees.map((item) => {
console.log(item.tests_taken);
let objectDetails = {
firstName: item.first_name,
lastName: item.last_name
};
console.log(item);
console.log(item.tests_taken[0]);
if (item.tests_taken[0]) {
console.log(item.tests_taken[0]);
item.tests_taken[0].forEach((test) => {
console.log(test[Object.keys(test)[0]]);
console.log('yo');
objectDetails = {
...objectDetails,
id: counter,
cefrLevel: test[Object.keys(test)[0]].overallScore.level,
cefrDescription:
test[Object.keys(test)[0]].overallScore.description,
overallScore: test[Object.keys(test)[0]].overallScore.score + '%',
assessmentDate: test[Object.keys(test)[0]].date
};
counter += 1;
emptyArray.push(objectDetails);
});
//console.log(emptyArray);
return objectDetails;
}
props.setEmployees(null);
});
setUsersArray(emptyArray);
console.log(usersArray);
return rowData;
}
}
useEffect(() => {
createData();
}, [props.employees]);
I have a series of data in which there is a form in every item. I try to use index in onSubmit event and when I check index of for loop in console, it shows the correct index, but when I check index of
handleSubmitR=(e, DetailsRoom, index)=>{console.log(index)}
it is different from the index in for loop.
For example, if I have 3 forms in one item the result of the index in for loop is
'01','02' ,'03'
but in onsubmit event the result of index is **
'03','03','03'
Any suggestions?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
resultEdit: {},
};
$.ajax({
url:"/json.bc",
type:"post",
success: (result) => {
this.setState({data: eval(result)});
}
})
}
renderHotel(){
return this.state.data.sort((a, b) => a.total - b.total).map((item,i)=>{
return (
<div class="items">
{this.renderDetailsRoom(item,i)}
</div>
)
})
}
renderDetailsRoom(DetailsRoom,i){
let lenfamilies = DetailsRoom.families.length
var indents =[];
for(var j = 0 ;j <lenfamilies;j++){
var numF = i;
var numS = j;
var stingF = numF.toString();
var stingS = numS.toString();
var index= stingF+stingS
**////
<!-----e.g. For two forms the result of consol.log(index) = '00' and '01'----->
/////**
indents.push(<form method="post" key={index} action={this.renderAction(DetailsRoom)} onSubmit={e => this.handleSubmitR(e, DetailsRoom, index)}><div class="Result">{this.state.resultEdit[index]}</div></form>)
}
return(
indents
)
}
handleSubmitR=(e, DetailsRoom, index)=>{
////
<!-----but the result of consol.log(index) in this part for both form are '01'----->
/////
console.log(index)
e.preventDefault();
return this.setState( prevState => ({
resultEdit: { ...prevState.resultEdit, [index]:'submitted'},
})) }
render() {
return (
<div>{this.renderHotel()}</div>);
}
}
ReactDOM.render(<App/>, document.getElementById('Result'));
I have service that gets me array of types:
ngOnInit() {
this.coreService.getByType( this.name ).subscribe(
response => { this.handleSuccess( response ); },
error => { console.error( error ); });
}
handleSuccess( coreTypes ) {
var data = [];
var pushedItems = [];
coreTypes.forEach( ( coreType ) => {
var entriesForType = [];
entriesForType.push( coreType );
if ( entriesForType.length > 0 ) {
entriesForType.forEach( entry => this.data.push( entry ) );
this.data = data;
if (data.length > 0) {
data.forEach( d => this.item.value = d && pushedItems.push(this.item));
}
if(this.gridOptions.api !== null){
this.gridOptions.api.setRowData( this.pushedItems );
}
}
});
}
Currently, this.data is creating me array like this this.data = ["one","two","three"]
What i need is to create array of object that will look like this
pushedItems = [{value:"one"},{value:"two"},{value:"three"}];
I defined item: Object; and in contstructor this.item = {value:""};
But in function, when i set this.item.value = d ... it keeps showing me error "Property 'value' does not exist on type 'Object' ...Any help to achieve array like pushedItems?
handleSuccess() {
const p = [];
this.coreTypes.forEach(coretype => {
let obj = {};
obj[coretype] = coretype;
p.push(obj);
});
}
handleSuccess() {
const p = [];
this.coreTypes.forEach(coretype => {
p.push({coretypes:coretypes});
});
}
Instead of pushing your object as:
arr.push(this.object);
you should just push it like:
arr.push({
value: this.object,
})